‘Quality in Everything We Do’
SMK Permas Jaya, Pasir Gudang, Johor.
C PROGRAMMING MODULE
SESSION 2013/2014
NAME : ________________________________
Prepared By: Mr. Irwan B. Ismail
(email : [email protected])
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
CONTENT PAGE
1. Syllabus ( Programming) 1–7
2. Introduction to Programming 8 – 13
3. Fundamentals of C Programming Language 14 – 30
4. Problem Solving in Programming 31 – 42
5. Control Structures 43 – 55
6. Functions 56 – 64
7. Data Structures 65 – 82
2
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
SECOND TERM: PROGRAMMING
3
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
4
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
5
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
6
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
7
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
6. Introduction to Programming
A computer program is a series of organised instructions that directs a computer to
perform tasks. Without programs, computers are useless.
A program is like a recipe. It contains a list
of variables (called ingredients) and a list
of statements (called directions) that tell
the computer what to do with the
variables.
Like a recipe, a program can be written in
different programming languages which
may express the steps differently
according to the programming language
syntax, but deliver the same end result.
Generations of programming languages
• A low-level programming language is a programming language that provides
little or no abstraction from computer’s microprocessor.
• A high-level programming language is a programming language that is more
abstract, easier to use, and more portable across platforms.
LEVELS OF PROGRAMMING LANGUAGE
8
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
FIRST GENERATION OF PROGRAMMING LANGUAGE
The first generation of
programming language, or
1GL, is machine language.
Machine language is a set of
instructions and data that a
computer's central
processing unit can execute
directly.
• Machine language statements are written in binary code, and each statement
corresponds to one machine action.
SECOND GENERATION PROGRAMMING LANGUAGE
• The second generation programming language, or 2GL, is assembly language.
Assembly language is the human-readable notation for the machine language
used to control specific computer operations.
• An assembly language programmer writes instructions using symbolic instruction
codes that are meaningful abbreviations or mnemonics.
• An assembler is a program that translates assembly language into machine
language.
• Since assembly language consist of human-readable abbreviations, the
assembler must first convert assembly language into machine-readable language
before the computer can readily understand its instructions.
9
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
THIRD GENERATION PROGRAMMING LANGUAGE
• The third generation of programming language, 3GL, or procedural language
uses a series of English-like words, that are closer to human language, to write
instructions.
• High-level programming languages make complex programming simpler and
easier to read, write and maintain. Programs written in a high-level programming
language must be translated into machine language by a compiler or interpreter.
• PASCAL, FORTRAN, BASIC, COBOL, C and C++ are examples of third generation
programming languages.
FOURTH GENERATION PROGRAMMING LANGUAGE
• The fourth generation programming language or non-procedural language, often
abbreviated as 4GL, enables users to access data in a database.
• A very high-level programming language is often referred to as goal-oriented
programming language because it is usually limited to a very specific
• application and it might use syntax that is never used in other programming
languages.
• SQL, NOMAD and FOCUS are examples of fourth generation programming
languages.
10
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
FIFTH GENERATION PROGRAMMING LANGUAGE
• The fifth generation programming language or visual programming language, is
also known as natural language.
• Provides a visual or graphical interface, called a visual programming
environment, for creating source codes.
• Fifth generation programming allows people to interact with computers without
needing any specialised knowledge.
• People can talk to computers and the voice recognition systems can convert
• spoken sounds into written words, but these systems do not understand what
they are writing; they simply take dictation.
• Prolog and Mercury are the best known fifth-generation languages.
(c) distinguish between compilers, interpreters, and translators;
TRANSLATOR
Sometimes two people cannot understand each other because they don’t
speak the same language. So they need the help of a third person who
understands both languages. This third person is known as a translator.
All software packages or programs are written in high-level languages, for
example, C++, Visual Basic and Java.
However, in order for the computer to be able to carry out the instructions,
the high-level languages must be translated into machine language before
the computer can understand and execute the instructions in the program.
The translation of high level languages to machine language is performed by
a translator.
PROGRAM
Have you ever wondered how your computer runs your favourite software?
Your favourite software is a program that consists of several instructions that
perform its operation.
11
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
A programmer will write a source code which consists of the instructions
needed to run a program.
Then the compiler or interpreter with assembler will translates the source
code into machine language which is made of a sequence of bits (eg.
01100011).
The computer will load the machine code and run the program.
ASSEMBLER
An assembler is a computer program for translating assembly language —
essentially, a mnemonic representation of machine language — into machine
language.
For example in intel 80836, the assembly language for the ’no operation’
command is NOP and its machine code representation is 10010000.
Example of assemblers are MACRO-80 Assembler and Microsoft MASM.
INTERPRETER
Interpreter is used to interpret and execute program directly from its source
without compiling it first. The source code of an interpreted language is
interpreted and executed in real time when the user execute it.
The interpreter will read each codes converts it to machine code and
executes it line by line until the end of the program.
Examples of interpreter-based language are BASIC, Logo and Smalltalk.
12
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
COMPILER
The source code (in text format) will be converted into machine code which
is a file consisting of binary machine code that can be executed on a
computer. If the compiler encounters any errors, it records them in the
program-listing file.
When a user wants to run the program, the object program is loaded into the
memory of the computer and the program instructions begin executing.
A compiled code generally runs faster than programs based on interpreted
language. Several programming languages like C++, Pascal and COBOL used
compilers as their translators.
13
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
7. Fundamentals of C Programming Language
(a) explain the C program development environment: edit, preprocess, compile, link,
load and execute;
C Program Development Environment
The system software necessary to develop C application program are
bundled into an integrated development environment (IDE)
A typical IDE contains text editor, C compiler, preprocessor, libraries,
other tools
The C programming environment has 2 components:
o Language – features to carry out basic operations (e.g.: store data
in variables, compare 2 data values, perform arithmetic operation, etc.)
o Libraries – routines to carry out operations not part of the
language (Standard libraries – e.g.: #include <stdio.h> & programmer-
defined libraries)
IDE – Microsoft Visual C++
14
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
C Development Environment
15
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
1. Prepare program (and data files)
Use a text editor to type your source program statements.
Assign a name to your source program file (.C) and save the file into disk
storage.
(optional) Use the text editor to create a data files. Assign names to the
data files (.txt or .dat) and save the files
2. Compile
Perform by a compiler.
C compiler has 2 separate programs: the preprocessor and the
translator.
Preprocessor reads the source code and prepares the code for the
translator.
Translator translates the code into machine language.
3. Link (“Build”)
As we will see later, a C program is made up of many functions.
The linker assembles all the functions into final executable program
(creates exe file).
4. Execute
If successful, it is ready for execution and get the output otherwise debug
the program
Types of programming errors: runtime error, syntax error and logic error;
Programming Error
There are three type of error that may be encountered during testing. The process of
solving the problems is called debugging’.
1. Design Error (logic)
Errors that caused by logic mistake. Outputs or decisions result produced are wrong
and not as what expected earlier.
2. Syntax Error
Error caused by programmers that didn’t fulfil the syntax or programming language
rules.
3. Run-time error.
Errors that cause by input data that doesn’t fulfil instruction requirement. This error
will result in the program implementation hang and display massages related to the
errors.
16
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
A Simple C Program Example
Output:
Elements of the C language
17
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Preprocessor directives
The C program line that begins with # provides an instruction to the C
preprocessor
It is executed before the actual compilation is done.
Two most common directives :
o #include
o #define
In our example (#include<stdio.h>) identifies the header file for standard
input and output needed by the printf().
Functions
Every C program has a function main
The function main usually calls input/output functions – printf(), scanf(), etc.
The word main is a C reserved word. We must not use it for declaring any
other variable or constant.
4 common ways of main declaration:
The curly braces { } identify a segment / body of a program
o The start and end of a function
o The start and end of the selection or repetition block.
Since the opening brace { indicates the start of a segment with the closing
brace indicating the end of a segment, there must be just as many opening
braces as closing braces } (this is a common mistake of beginners).
Statements
A specification of an action to be taken by the computer as the program
executes.
Each statement in C needs to be terminated with semicolon (;)
18
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example:
#include <stdio.h>
void main(void)
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
}
Statement has two parts :
Declaration
o The part of the program that tells the compiler the names of
memory cells in a program
int age, total=0;
Executable statements
o Program lines (excluding comments) that are converted to
machine language instructions and executed by the computer.
A list of statements may be enclosed in braces { } (known as
compound statement)
General form of a C program
preprocessor directives #include <stdio.h>
main function heading void main(void)
{
{
declarations executable // statement(s);
statements }
}
C statements can extend over more than one line. Example:
printf (“\n Your coins are worth %d dollars and %d cents.\n”, dollar, change);
You can write more than one statement on a line (but not recommended).
Exparminptfle(“:Enter your name:”);
scanf(“%”,&Name);
19
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
C program skeleton Preprocessor directives
Function
#include <stdio.h> main
void main(void) Start of segment
{
statement(s);
}
End of segment
Use C language special words: reserved words, standard identifiers, and standard
functions.
Reserved Words/Keywords
Keywords that identify language entities such as statements, data types,
language attributes, etc.
Have special meaning to the compiler, cannot be used as identifiers in our
program.
Should be typed in lowercase.
Must not be used as variables!!
Keywords may be classified into:
o Data type* related
o Flow of control related
o Miscellaneous keywords
Data Type Related Keywords
A number of keywords are used to identify or qualify specific data types:
Auto float union
Extern int void
Register long volatile
Static short struct
Const signed double
char unsigned
20
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Flow of Control Related Keywords
Keywords used for handling the flow of control in C programs:
break while
case if
goto else
continue for
default switch
do return
Miscellaneous Keywords
The keywords that don’t fall under either of the previous categories:
- Enum
- sizeof
- typedef
____________________________________________________________________
7.2 Basic data types
There are 4 basic data types :
int
float
double
char
int To declare numeric program variables of integer type - whole numbers, positive
and negative
Example:
int number;
number = 12;
float
fractional parts, positive and negative
Example:
float height;
height = 1.72;
21
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
double
To declare floating point variable of higher precision or higher range of numbers -
exponential numbers, positive and negative
Example:
double valuebig;
valuebig = 12E-3;
char Equivalent to ‘letters’ in English language
Example of characters:
o Numeric digits: 0 – 9
o Lowercase/uppercase letters: a - z and A – Z
o Space (blank)
o Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
o Single character
Example:
char my_letter; The declared character must be
my_letter = 'U'; enclosed within a single quote!
In addition, there are void, short, long, etc.
Strings as a Derived Data Type
A string is a sequence of characters that is treated as a single data item.
In C a string variable is represented in a one-dimensional array of type char.
The max length of the string constant that can be stored in a character array of
size n is n-1
string declared as one-dimensional array is always terminated by NULL or ‘\0’.
Example:
char report_header[41] = “Annual Report”;
Constants
Entities that appear in the program code as fixed values.
Example:
const double INTEREST_RATE = 0.015;
4 types of constants:
Integer constants
Floating-point constants
Character constants
Enumeration
22
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Integer constants
o Positive or negative whole numbers with no fractional part
o Example:
const int MAX_NUM = 10;
const int MIN_NUM = -90;
Real / Floating-point constants
o Positive or negative decimal numbers with an integer part, a decimal
point and a fractional part
Example:
const double VAL = 0.5877e2;
(stands for 0.5877 x 102)
+194.143, -416.41
Character constants
A character enclosed in a single quotation mark
Example:
const char LETTER = ‘n’;
const char NUMBER = ‘1’;
But, to print single quotation mark ‘ require backslash (known as escape sequence*)
since ‘’’ is illegal.
printf(“%c”, ‘\’’);
- prints a single quotation mark on screen
printf(“%c”, ‘n’);
- prints the letter n on the screen
printf(“%c”, ‘\n’);
- move cursor to the beginning of a new line
Example - 1
#include <stdio.h>
void main(void)
{
const double KMS_PER_MILES = 1.609;
double miles, kms;
printf(“Enter the distance in miles:”);
scanf(“%lf”,&miles);
kms = KMS_PER_MILES * miles;
printf(“\nThat equals %f kilometer.\n ”, kms);
}
23
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example – 2
#include <stdio.h>
#define KMS_PER_MILES 1.609
void main(void)
{
double miles, kms;
printf(“Enter the distance in miles:”);
scanf(“%lf”,&miles);
kms = KMS_PER_MILES * miles;
printf(“\nThat equals %f kilometer.\n
”, kms);
}
String Literals/ String Constants
A sequence of any number of characters surrounded by double quotation
marks “ ”.
Example: “This is a string constant.”
“Hello \”John”\.”
Example of usage in C program:
printf(“My name is David Beckham.”);
simply print the string constant
My name is David Beckham.
Cannot print double quotation marks unless enclosed with backslashes.
Punctuators (Separators)*
Symbols used to separate different parts of the C program.
These punctuators include: [ ] ( ) { } , ; “: * #
Usage example:
main()
{
printf(“Testing.”);
}
Operators
Tokens that result in some kind of computation or action when applied to
variables or other elements in an expression.
Example of operators: * + = - / < >
Usage example:
result = total1 + total2;
24
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Summary :
7.3 Expressions and operators
ARITHMETIC OPERATORS
Operators are the representations that are used to direct to compiler to perform
operations on the identifiers. They are used to modify the value of any identifiers. An
operator is represented by an equation symbol, ‘=’. The value of the identifier on the left,
changes according to the operation on the right hand side of the equation.
Example :
x = 2; /* the x identifier is assign by the value of 2*/
x = x + 5 /* the x identifier is updated with the sum of the initial value of x and 5*/
There are five types of operators:
(a) Assignment
The single identifier on the left hand side of the equation, is known as lvalue which will
be represented by identifiers and operators on the right. Assignment to more than one
identifier is permitted, but C compiler will calculate the value of the far right phrase, and
then the value will be assign to the left hand side identifier, one by one.
Example :
x = 2;
x = y = 2;
x + 1 = x; (This assignment is not allowed)
a = b + 10 = c; (This assignment is not allowed)
25
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
(b) Mathematic
There are 5 basic mathematical operators:
+ Addition Integer and float
- Subtraction Integer and float
* Multiplication Integer and float
/ Division Integer and float
% Balance(modulus) Integer only
C will executes * and / operations, before – and + operations.
Example :
1+2*5
The operation will be executed first is 2*5 = 10 and followed by 1 + 10 = 11
(c) Complex Assignment(Umpukan Majmuk)
If the assignment operator is combined with a mathematic operator, it will produce
a complex assignment operator.
Exemple : x += y; ( Definition : x = x + y )
total *= number; ( Definition : total = total * number)
(d) Increment and Decrement
“++” and “—“ symbols are used to show the operation of adding an integer value of
1 or subtracting an integer value of 1 from an interger identifier.
Example :
x++; (Definition : x = x + 1) -Post-increment
++x; (Definition : x = x + 1) -Pre-increment
y--; (Definition : y = y - 1) -Post-decrement
--y; (Definition : y = y - 1) -Pre-decrement
Operators program example:
#include<stdio.h> 26
main()
{
int x = 10, y = 5;
printf(“ X = %i”,x);
printf(“ \t Y = %i\n”,y);
printf(“ X + Y = %i\n”,x + y);
printf(“ X x Y = %d\n”,x * y);
printf(“ X/Y = %i\n”,x/y);
printf(“ The balance of X devide by Y = %d\n”, x%y);
printf(“%d\t”, x++);
printf(“%d\n”, ++x);
printf(“%d\t”, x--);
printf(“%d\t”, --x);
x = x++;
printf(“%d\t”,x);
x = 10;
x = x--;
printf(“%d”,x);
return 0;
}
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Relation Operators
This operation will produce the value of 0 or 1.
0=false, 1=true
To determine the relation between an operation with another operation, relation
operators are used.
Relation Symbol Explanation
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
= = Equal to
!= Not equal
Logic Operators
Logic operators are used to form more complex conditions by combining simple
conditions.
Logic operators are as bellow:
Logic Symbol Explanation
&& And
|| Or
! Not
Priority arrangement for logic operations and relation operations are as follows:
Highest : !
> >= <=
&&
Lowest : ||
Condition Operator (?:) :
If any condition need to apply to a phrase, condition operator that can be used is
‘?:’
Format : condition? 1st phrase: 2nd phrase;
Example:
ans=(m >0)? 10:100;
The m > 0 condition is tested, if the condition is true (may be m=5), then the
value of 10 will be assign to ans. On the other hand, if the condition is false(may
be m=-8), then the value of 100 will be assign to ans.
27
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Equality operator
The following table describes the two equality operators:
Operator Usage
== Indicates whether the value of the left operand is equal to the value of
the right operand.
!= Indicates whether the value of the left operand is not equal to the value
of the right operand.
Note:
The equality operator (==) should not be confused with the assignment (=) operator.
For example,
if (x == 3)
evaluates to true (or 1) if x is equal to three. Equality tests like this should be
coded with spaces between the operator and the operands to prevent
nintentional assignments. while
if (x = 3)
is taken to be true because (x = 3) evaluates to a nonzero value (3). The
expression also assigns the value 3 to x.
7.4 Input and output
Input/output operations
Input operation
-an instruction that copies data from an input device into memory
Output operation
-an instruction that displays information stored in memory to the output
devices (such as the monitor screen)
he input/output operations are performed by C input/output functions.
The standard C functions predefined in stdio.h header file include:
-printf()
-scanf()
-getchar()
-putchar()
The Output Function printf()
Used to send data to the standard output (usually the monitor) to be printed
according to specific format.
28
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Syntax:
printf(FormatControlString);
printf(FormatControlString, PrintList);
FormatControlString is a combination of characters, format specifier and
escape sequence.
PrintList is any constants, variables, expressions, and functions calls
separated by commas.
Example:
printf(“Thank you”);
printf(“Total sum is: %d\n”, SUM);
%d is a placeholder (format specifier)
o marks the display position for a type integer variable
\n is an escape sequence
o moves the cursor to the new line
Formatting Output
Format specifier (placeholder)
o Tells the printf() function the format of the output to be printed put.
Format Specifier Output Type
%d
%c for integers
%f, %lf for characters
%e
%s for floating-point values in conventional notation
for floating-point values in scientific notation
for sequence of characters (string)
Output statements Prints on the screen
printf(“%d”, 15); 15
printf(“Hello”); Hello
printf(“%s”, “Hello”); Hello
printf(“%c”, ‘a’); a
printf(“%f”, 1.25); 1.250000
printf(“%e”, 1.25); 1.250000e+00
printf(“%s”, name); John D
(assume name[20]=“John D”)
29
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Escape Sequence
is used in the printf() function to do something to the output.
The common escape sequence
Escape Sequence Meaning
\n New line
\t Horizontal tab
\v Vertical tab
\b Backspace
\0
\\ NULL
Prints a backslash (\)
The Input Function scanf()
Read data from the standard input device (usually keyboard) and store it in a
variable.
The general format is pretty much the same as printf() function.
Syntax
scanf(FormatControlString, InputList);
InputList – one or more variables addresses, each corresponding to a format
specifier in the FormatControlString.
One format specifier for each variable in InputList.
The two or more variables in InputList must be separated by commas.
Each element of InputList must be an address of a memory location (using
prefix & address operator)
int printf scanf
float %d %d
double %f %f
char %f %lf
string %c %c
%s %s
Example
#include <stdio.h> 30
main()
{
int Age;
printf(“Enter your age: “);
scanf(“%d”, &Age);
printf(“Your age is: %d”,Age);
}
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
8. Problem Solving in Programming
PROGRAM DEVELOPMENT PHASES
In program development, there are five main phases. These phases are a series of
steps that programmers undertake to build computer programs. The program
development phases guide computer programmers through the development of a
program.
PROBLEM ANALYSIS PHASE / PROGRAM CLARIFICATION
During the problem analysis phase, the programmer will interview the client to find out
what the client’s needs are.
For example, the client might be a school that wishes to set up a school registration
program. So the school administrator might tell the programmer that they need to record
students’ data such as name, date of birth, gender, class, parents’ names, address and
contact numbers.
PROGRAM DESIGN PHASE
Based on that, the programmer will design a flow chart that represents the needs of the
client, which in this case is the school registration program.
CODING PHASE
Once the flow chart is confirmed, the programmer will perform coding.
TESTING AND DEBUGGING PHASE / program test and program documentation
The school registration program will be tested by the users at the client’s site. In this
case, it will be the school office administrators. If there are any errors, the programmer
will do a debugging of the program.
DOCUMENTATION PHASE
After this, the programmer will complete the documentation for the program; this
includes the user manual, a clear layout of the input and output records and a program
listing.
31
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Problem Solving
Objectives
Using computers in problem solving
Software development methods (SDM)
Requirements specification
Problem analysis
Design and algorithmic representation
Implementation
Testing and verification
Documentation
Using Computers in Problem Solving
Def: Problem solving is a process of transforming the description of a problem
into the solution of that problem by using our knowledge of the problem domain
and by relying on our ability to select and use appropriate problem-solving
strategies, techniques and tools.
Computers can be used to help us in doing problem solving.
Software Development Method (SDM)
Consists of the following steps:
Requirements specification
Problem analysis
Design the algorithm to solve the problem
Implementation
Testing and verification
Documentation
1. Requirements Specification
State the problem clearly and unambigously (single interpretation) to
understand exactly:
a. what the problem is
b. what is needed to solve it
c. what the solution should provide
d. if there are constraints and special conditions.
2. Problem Analysis
In the analysis phase, we should identify the following:
b. Inputs to the problem, their form and the input media to be used
c. Outputs expected from the problem, their form and the output media to
be used
d. Special constraints or conditions (if any)
e. Formulas or equations to be used
32
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example Case: Apples
Problem: Compute and display the total cost of apples given the number of
kilogram (Kg) of apples purchased and the cost per Kg of apples.
Input:
Quantity of apples purchased (in Kg)
Cost per Kg of apples (in RM per Kg)
Output:
Total cost of apples (in RM)
Constraint: N/A
Formula:
Total cost = Cost per Kg X Quantity
3. Design the algorithm to solve the problem
Purpose: to develop and verify algorithm
An algorithm is a list of steps to be executed with the right order in which these
steps should be executed.
Writing the algorithm is a difficult task use top-down design (divide and
conquer approach)
Top-down design:
List the major steps (most algorithm consist of at least the following):
- Get the data
- Perform the computations
- Display the result
Perform algorithm refinement – the step(s) may need to be broken down into
a more detailed list of steps
Verify that the algorithm works as intended – perform desk check.
Example Case: Apples
1. Major steps:
1. Get the Quantity of apples purchased (in Kg)
2. Get the Cost per Kg of apples (in RM per Kg)
3. Compute the total cost of apples purchase
4. Display the computed total cost
2. Refinement:
1. Get the Quantity of apples purchased (in Kg)
2. Get the Cost per Kg of apples (in RM per Kg)
3. Compute the total cost of apples purchase
3.1 The total cost = Cost per Kg X Quantity
4. Display the computed total cost
33
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
summary:
What is algorithm ?
An algorithm is an ordered set of unambiguous, executable steps, defining a terminating
process.
Algorithm:
Must may have input(s) and must have output(s)
Should not be ambiguous (there should not be different interpretations to
it)
Must be general (can be used for different inputs)
Must be correct and it must solve the problem for which it is designed
Must execute and terminate in a finite amount of time
Must be efficient enough so that it can solve the intended problem using
the resource currently available on the computer
Specifying the order in which the steps are to be executed is important.
Example algorithm for getting out of bed and prepare to go to work:
34
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
If the same steps are performed in a slightly different order:
Get out of bed
Take off pajamas
Take a shower
Get dressed
What would be the result?
Get out of bed
Take off pajamas
Get dressed
Take a shower
An algorithm can be represented using pseudocode or flowchart.
Any algorithm can be described using only 3 control program structures:
sequence, selection and repetition.
Pseudocode
Pseudocode is a semiformal, English-like language with limited vocabulary that
can be used to design and describe algorithms.
Criteria of a good pseudocode:
Easy to understand, precise and clear
Gives the correct solution in all cases
Eventually ends
Flowchart
Flowcharts is a graph used to depict or show a step by step solution using
symbols which represent a task.
The symbols used consist of geometrical shapes that are connected by flow
lines.
It is an alternative to pseudocoding; whereas a pseudocode description is verbal,
a flowchart is graphical in nature.
The Symbols – FLOW CHART
Terminal - indicates the beginning and
end points of an algorithm.
Process - shows an instruction other than
input, output or selection.
Input-output - shows an input or an output
operation.
Disk storage I/O - indicates input from or
output to disk storage.
35
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Printer output - shows hardcopy printer
output.
Selection - shows a selection process for
two-way selection.
Off-page connector - provides
continuation of a logical path on another
page.
On-page connector - provides
continuation of logical path at another point
in the same page.
Flow lines - indicate the logical sequence
of execution steps in the algorithm.
1. Sequence Control Structure
A series of steps or statements that are executed in a specific order.
The beginning and end of a block of statements can be optionally marked with
the keywords begin and end.
The structure:
Statement – 1
Statement – 2
Statement – n
Example:
begin read birth date from user
end calculate the difference between the birth date and today’s date
print out the exact age of the user
Begin
Get
Birth date
Calculate Age =
different
of birth date and
current date
Print Age
End
36
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
2. Selection Control Structure
Defines two courses of action depending on the outcome of a condition. A
condition is an expression that is either true or false.
The keyword used are if and else.
The if selection structure:
if <condition>
<then-statement(s)>
The if/else selection structure:
if <condition>
<then-statement(s)>
else
<else-statement(s)>
Example:
Pseudocode:
if carrymarks is greater than or equal to 60
print “Passed”
else
print “Failed”
The C statements:
if (carrymarks >= 60)
printf(“Passed\n”);
else
printf(“Failed\n”);
The C statements correspond closely to the pseudocode statements
The if/else structure:
False Condition True
Else- Then-
Statement(s) Statement(s)
37
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example:
Begin
Get marks
False marks True
>= 60?
Print Print
“Failed” “Passed”
End
3. Repetition Control Structure
Allows the programmer to specify that an action is to be repeated until some
terminating condition occurs.
The keyword used is while.
The while structure:
while <terminating condition> Condition True
statement(s)
False
Statement(s)
Example:
Problem: Write a program that reads and displays the age of 10 people (one after
another).
For this problem, we need a way to count how many people whose age have been
processed (read and displayed). Therefore, we introduce a concept of counter, a
variable used to count the number of people whose age have been processed by the
program.
Pseudocode
38
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Flow Chart
Program code
4. Implementation
The process of implementing an algorithm by writing a computer program using a
programming language (Example, using C language).
The output of the program must be the solution of the intended problem.
Example Case: Apples
39
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
5. Testing and Verification
Program testing is the process of executing a program to demonstrate its
correctness
Program verification is the process of ensuring that a program meets user-
requirement
After the program is compiled, we must run the program and test/verify it
with different inputs before the program can be released to the public or
other users (or to the instructor of this class)
Example Case: Apples
Inputs Expected Output Actual Output
2 8.00
4.00
50 125.00
2.50
STANDARD ALGORITHMS
SORTING
Data sorting is a process of comparing and rearranging data into a specific order, either
ascending or descending manner. Sorting is an important algorithm in computer
programming.
There are a few sorting approaches, such as insertion sort and bubble sort.
(a) Insertion Sort
The basic concept of insertion sort is similar to inserting an element into a sorted list.
For ascending order, all the right values are greater than the left values.
Algorithm: 40
Start
For(i=0 ; i < n ; add 1 to i)
Start
For(k=i-1 ; k >= 0 ; minus 1 from k)
Start
If(A[k] > A[i])
Start
Tmp=A[i]
A[i]=A[k]
A[k]=tmp
End_if
End_k
End_ i
Stop
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Insertion Sort:
Arrange the following values in an ascending order:
67 33 21 84 49 50 75
67
33 67
21 33 67
21 33 67 84
21 33 49 67 84
21 33 49 50 67 84
21 33 49 50 67 75 84
(b) Bubble Sort
Bubble sort compares two continuous numbers in a group of numbers.
Beginning with comparing the first two elements in an array.
- If the elements are in order, leave them.
- If the elements are not in order, swap their position.
Then, compare the third and fourth elements. If they are not in order, the same
procedure applied, swap their position. On the other hand, just leave them alone.
Repeat the same process until the last two elements are compared. This concluded
the first round of sorting.
Start the second round with the same process until all the elements in the array are
perfectly in order.
Algorithm:
Start
max = no – 1, j=0
Repeat
start
i=0
Repeat
start
If xi > xi+1
Swap xi and xi+1
i=i+1
stop
while i<max-1
j = j +1
stop
While j<max
Stop
41
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Bubble Sort Example:
Sort the following numbers in ascending order.
67 33 21 84 49 50 75
Round 1
67 33 21 84 49 50 75
33 67 21 84 49 50 75
33 21 67 84 49 50 75
33 21 67 84 49 50 75
33 21 67 49 84 50 75
33 21 67 49 50 84 75
33 21 67 49 50 75 84
Round 2
33 21 67 49 50 75 84
21 33 67 49 50 75 84
21 33 67 49 50 75 84
21 33 49 67 50 75 84
21 33 49 50 67 75 84**
21 33 49 50 67 75 84
21 33 49 50 67 75 84
All the numbers are in order after the forth comparing in
the second round.
SEARCHING
Searching is a process which searches for an array’s element which is equivalents
with a search value.
There are a few approach used for searching. Among them is linear search. Linear
search compares avery elements with a given search value, without arranging the array
elements in any order. As a result, the program has to test the search value with an
average of half the number of the array’s elements.
Algorithm:
Start
max = no – 1, i=0
Read value
Repeat
start
if value = xi
found and stop
i=i+1
stop
While i<max-1
Stop
42
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
9. Control Structures
Conditional statements
Selection Structure
Defines two courses of action depending on the outcome of a condition. A
condition is an expression that is either true or false.
The 4 general form of selection structure:
1. if(Expression) 2. if (Expression)
then-statement; then-statement;
/* end_if */ else
else-statement;
/* end_if */
if Selection Structure
Syntax:
if (Expression)
then-statement;
/* end_if */
The then-statement is only executed if the condition is satisfied (Expression
returns True).
43
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example: if (status == 1)
printf(“Kids!!\n”);
/* end_if */
if (status == 2)
printf(“Adults!!\n”);
/* end_if */
Example: #include <stdio.h>
main(void)
}
int status;
printf(“Enter your membership status:”);
scanf(“%d”, &status);
if (status == 1)
printf(“Kids!!\n”);
/* end_if */
if (status == 2)
printf(“Adults!!\n”);
/* end_if */
}
if … else Selection Structure Example:
if (age < 5)
Syntax: status = 1;
else
if (Expression) status = 2;
then-statement; /* end_if */
else
else-statement;
/* end_if */
If the condition is satisfied (Expression returns True), the then-statement will
be executed. Otherwise, the else-statement will get executed.
44
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example
#include<stdio.h> Assume:
void main ( ) gender is M
{ age is 35
char gender;
int age;
float car_loan;
printf(“Enter your gender (f/F or m/M) and age:”);
scanf(“%c %d”, &gender, &age);
if ((gender==‘f’ || gender==‘F’) && age>20)
car_loan=200000.00;
else
car_loan = 500000.00;
/* end_if */
printf(“Your car loan is %.2f\n”, car_loan);
}
Nested if … else
Is an if…else statement with another if…else statements inside it.
The else if statement (in the nested if…else) means that if the condition
above is not satisfied, then try checking this condition. If any one of the
condition is already satisfied, the other conditions will be ignored completely.
Example if (score >= 90)
Example printf(“A\n”);
else if (score >= 80)
printf(“B\n”);
else if (score >= 70)
printf(“C\n”);
else if (score >= 60)
printf(“D\n”);
else
printf(“F\n”);
/* end_if */
#include<stdio.h> 45
void main()
{
int i;
printf("Enter a number between 1 and 4: ");
scanf("%d", &i);
if(i==1)
printf("one\n");
else if(i==4)
printf(“four\n");
else
printf(“Unrecognized number\n");
/* end_if */
}
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
if…else with Compound Statements
In the examples that we have seen so far, there is only one statement to be
executed after the if statement.
If we want to execute more than one statement after the condition is satisfied, we
have to put curly braces { } around those statements to tell the compiler that they
are a part of the then-statement or else-statement.
Example
…
if (score >= 90) {
printf(“You have done very well\n”);
printf(“Please see your lecturer to get a present\n”);
}
else if (score >= 60) {
printf(“You have passed the course\n”);
printf(“But do not ask for any present from your lecturer\n”);
printf(“Go and celebrate on your own\n”);
}
…
Selection Structure using ? : Operators
/* alternative if-else demonstration */
#include <stdio.h>
void main( )
{ int mts, hr;
printf(“Enter time (minutes): “);
scanf(“%d”, &mts);
:
mts > 60 ? hr++ : mts += mts;
printf(“\nDone!\n”);
}
Selection Structure Using switch Statement
A switch statement is used to choose one choice from multiple cases and one
default case.
Syntax:
switch (ControllingExpression) • The break statement is needed so that once a
{ case has been executed, it will skip all the
other cases and go outside the switch
case constant 1: statement; statement. If the break statement is omitted,
break; the execution will be carried out to the next
alternatives until the next break statement is
case constant-n: statement; found.
break;
default: statement;
}/* end_switch */
• The default clause is executed if the cases
are not met. 46
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
The value for ‘case’ must be integer or character constant only.
o Examples:
switch (number) {
case 1 :
statement;
break;
switch (color) {
case ‘R’ :
statement;
break;
The order of the ‘case’ statement is unimportant
Example
#include <stdio.h> ControllingExpression
void main(){ must be of type int or
int i; char only
printf("Enter a number between 1 and 4: ");
scanf("%d", &i);
switch(i){
case 1 : printf(“one\n”);
break;
case 4 : printf(“four\n”);
break;
default :
printf(“Unrecognized number\n”);
} /* end_switch */
More Example
#include <stdio.h> 47
void main()
{
int major_code;
printf("Enter your majoring code: ");
scanf("%d", &major_code);
switch(major_code){
case 1 :
case 3 :
case 5 : printf(“Science Student\n”);
break;
case 2 :
case 4 : printf(“Art Student\n”);
} /* end_switch */
}
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Loop statements
Loop control statements
Repetition Structure
Used to repeat a block of statements a finite number of time (loop) until a certain
condition is met without having to write the same statements multiple times.
Two design of loop:
Counter-controlled – loop depends of arithmetic or conditional expression.
Sentinel-controlled – loop depends on a sentinel value.
Counter-controlled:
o To execute a number of instructions from the program for a finite,
pre-determined number of time
o Loop depends of arithmetic or conditional expression.
Sentinel-controlled:
o To execute a number of instructions from the program indifinitely
until the user tells it to stop or a special condition is met
o Loop depends on a sentinel value.
There are 3 types of repetition structure:
1. while (LoopControlExpression)
LoopBody-statement;
/*end_while */
2. do
LoopBody-statement;
while (LoopControlExpression);
/* end_do_while */
3. for (InitializationExp; LoopControlExp; UpdateExp)
LoopBody-statement;
/*end_for */
Exp = Expression
48
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Repetition: while Statement
o Syntax: while (LoopControlExpression)
LoopBody-statement;
/*end_while */
o As long as the condition is met (the LoopControlExpression returns true), the
statement inside the while loop will always get executed.
o When the condition is no longer met (the LoopControlExpression returns false),
the program will continue on with the next instruction (the one after the while
loop).
The Counter-controlled while Statement: Example
... Counter-controlled while loop
int total = 0;
while (total < 5) total is the loop counter
{ variable
printf(“Total = %d\n”, total); In this case, this loop will
total++; keep on looping until the
} counter variable is = 4.
... Once total = 5, the loop will
terminate
#include<stdio.h> #include<stdio.h>
main ( ) main ()
{ {
printf(“Hello World\n”); int num = 1;
printf(“Hello World\n”);
printf(“Hello World\n”); while(num <=5)
printf(“Hello World\n”); {
printf(“Hello World\n”);
} printf("Hello World\n");
num++;
Avoid having to write the } /*end_while */
same statements }
multiple times.
49
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Infinite Loop
If somehow the program never goes out of the loop, the program is said to be
stuck in an infinite loop.
The infinite loop error happens because the LoopControlExpression of the
while loop always return a true.
If an infinite loop occurs, the program would never terminate and the user
would have to terminate the program by force.
Examples Output :
#include<stdio.h> 0
void main() 5
{ 15
30
int i=0, x=0;
while(i<20) { x = 30
if(i % 5 == 0){
x += i;
printf("%d\n", x);
}
i=i+1;
}/* end_while */
printf("\nx = %d\n", x);
}
Example
#include<stdio.h> Output
#define MAX 8 :
void main() 1
{ 1
2
int f1, f2, f3; 3
int count = 1; 5
f1=f2=1; 8
13
while(count<=MAX) { 21
printf("%d\n", f1);
f3=f1+f2;
f1=f2;
f2=f3;
count=count+1;
} /* end_while */
}
50