0% found this document useful (0 votes)
243 views

Final Document

This document provides a summary of a 60-page report on programming best practices written by an expert programmer. It discusses two main topics covered in the report: 1. Recommendations for structuring programming code in a clear, logical way using appropriate formatting and naming conventions to make the code more readable and maintainable. 2. Guidelines for writing code that is well-organized, modular, and follows principles of object-oriented design, including proper encapsulation, abstraction and separation of concerns. The summary emphasizes writing "self-documenting code" that is intuitive for other programmers to understand through judicious use of comments.

Uploaded by

Not my documents
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
243 views

Final Document

This document provides a summary of a 60-page report on programming best practices written by an expert programmer. It discusses two main topics covered in the report: 1. Recommendations for structuring programming code in a clear, logical way using appropriate formatting and naming conventions to make the code more readable and maintainable. 2. Guidelines for writing code that is well-organized, modular, and follows principles of object-oriented design, including proper encapsulation, abstraction and separation of concerns. The summary emphasizes writing "self-documenting code" that is intuitive for other programmers to understand through judicious use of comments.

Uploaded by

Not my documents
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 229




 

 
 1  !"#$%&
# 
 2 ( $%)# !"#*%
) # !(
%)
)% ) 

 
  !"##  *(!"#
%) ,
-(()"
  (./ -0 # ! ) )*
)1 
(*)"() #03# *
*) 
 /) 
*
 
 4()" - !(5 !"#  4 

 (/$ $ # 6   ( 3)#  )7"4
(  "4)() 
   6) #"4
)"4
 

) /($9($/(6
 
**3% )% $"
7 *("*) 
# "
 
 
, ) (*
#*)**(!"# ) 1 (
 " 0  (0 #)" 0(
 /
",9 "
  /. - - (0 #)" 0( # 6) - 
03*%$%&  )03: 7   
#6!"#*3% !(
.))*) 

% $ ;"=
 #"4
(!"#
 
 !(  
)!("4
) /#*)* /
"4 /#*)**(!"#) "(0 #)/  
:(03"( # "4 /#*)*!"/ / "
- 6)()
 
#6!"# )"()()  
%)%
 , !"# # ,( 
#
0( # . 
)03$()! *
! % ** .- - .()
 
#6. ?3)" (

# -( .@)-(( ((0  ((0"
, !!(  .-  ) # ((
 .-" /.
-$% %)
"# 
#6 " !(/
) . 

*
 !(5 ()() )0 ( :A "    .-(()
$%

$ 5% #
/ (0 ( .C- /  
 6"
" )
# *

0 ( .// $ (
" : - . 
* 

28/04/2010

1 of 229


      
60 /!)
(Master Teacher in Programming)

 

 
 1 # 
 2 ( 
!"#$%& # ( $%)# !"#*%
)) # ?3) 


%) )

%  !"## ) *(!"## 

# 
-(()" (./ -0 # ! ) )*
)1  (
 *)"()
)% .))"*) 
 $ ;"=
 #"4
(
!"# 
 !(  
)!("4
)/
#*)* / "4 / "(0 #)/ ( :(03"()
"4 /#*)*!"/%) /
,." ) *)
% $
1. 

* ,   )(*
6* *

)# )(*)"4)1 6 6  (!("
9(# 9)C)
2. 

* ,$! ) )*
# *
% :  
6#"4
)1 6
3. 

* ,*(!"# 6#"4
6 
6  !(!"#*( )/# ((!(6 
4. 

* ,6 
",($ 
# ((

  / *


"##*)*#"4(!"#%) / 
%) , ( ,*#*)*)*)
$% " (

 

!
 "    #$% 
9
Problem-based learning
#).
*

Problem Solving Steps
 *

 6- ) ,
 )1
9
    %&' 
! ) )!"#
!"# # # ) ())(
" 0#"
!"# *$
 6$%
")* -())(
6 )*
 # # ) *

# 6
 )
/ Editor/Compiler
6)#)$ (if, switch)
6)#?%6 (for, while, do while)
Function and Procedure
Parameter passing
Structures
 
( "    ") *!
24
1D Array, 2D Array, Stack,

Queue, Tree, Graph
 #$%       
18
()!(#*)* "
(0 #)/ #
!" " 0
+$$   
4
 3-12 C9  2553

28/04/2010

2 of 229

+$$   
     $-
.$ -
#$%   "  -

$!#$%  
       (60 !)

3

%
08.30 - 09.00
09.00 - 09.30
09.30 - 12.00

%&' 

09.00-12.00

) (
:"
"?,"4!"# $,3)"4# ." 
 /*(!"# ,3)  
)0
(
 !( 6, (
" 7)%
predicates as conditions for selections and iterations
subprograms: procedures and functions
pointers
array and pointers
structures as aggregation of data
self-referential structures and pointers
%#)
 *   Post-Test 6 3 / $
 !!(  0 (
*)03())
#"49 
-0 9 
 "    #$%  (!())"4
 

*/)/)
Problem-based learning
Problem Solving Steps
 "    #$%  ()
Problem-based learning
Problem Solving Steps
    %&' 
! ) )!"#
" 0#"
6 )*
 # # ) *

# 6
 )
/ Editor/Compiler
6)#)$ (if, switch)
6)#?%6 (for, while, do while)
Function and Procedure
Parameter passing (with Pointer)
Structures
    %&'  ()

13.00-16.00
09.00-12.00

1D Array

13.00 - 16.30

09.00-12.00
13.00-16.30

13.00-16.00

28/04/2010

9 +$
$     %&'   %!
#)" 9*
 ( if-else-if, switch)
 *

 6- ) ,
 )1
!"# # # ) ())(
()*


3 of 229

$


7

%
09.00-12.00

%&' 
2D Array (Sorting and Searching algorithms)

13.00-16.00

9 +$
$     %&'   '
#)" 9*
 ( if-else-if, switch)
 *

 6- ) ,
 )1
!"# # # ) ())(
$%   #  (    
Structures and Self-Referential Structures
Dynamic Memory Allocation and Linked-list

09.00-12.00

13.00-16.00
09.00-12.00
13.00-16.00
09.00-10.00
10-00-12.00

10

13.00-16.00

$%   #  (    


Stack, Queue, Tree and Graph
"  (("   "   * "%" T."  (( " "%-" )
" T."  (( " "%-" )
()
" T."  (( " "%-" )
()

11

09.00-12.00

12

13.00-16.00
09.00-12.00

(
 Post-test

).
 $       (
  1
("=)

13.00-15.00

).
 $       (
  2
(Cs)

)" V% (     %  $ "


   

15.00-16.00

 *"
      

*. )*()(( 80 3)  :t *  #
(
 
-u #")%

"
 
$X
0-49
50-79
80-100

28/04/2010


  (
  1 ("=) (
  2 (Cs)
25
40
35




4 of 229

$

  


      

28/04/2010

5 of 229


4 (Hardware)
(Software)

2.1



(Computer Hardware)

( .. 2525)

3 (Input Data)
(Data Processing) (Output Result) 2.1


28/04/2010

6 of 229

(Processing)

(Input)

(Output)

(Memory)

2.2


5 (Central Processing Unit) (CPU)
(Input Unit) (Output Unit) (Main Memory)
(Secondary Memory)
(Case)

(Monitor)

(Keyboard)

28/04/2010

7 of 229

(Central Processing: CPU)


(Case)

(Control Unit)




(Microprocessor)

(Intel)

Intel-Compatible Processor
(AMD) (Cyrix)

workstation

28/04/2010

8 of 229


(port)
(Input Devices)


(Keyboard) (Mouse)
(Scanner) (Digital Camera)

(Keyboard)



101 105
(Alphanumeric key) (Numeric key)
(Function key) F1 F12
Esc,
PrintScreen

28/04/2010

9 of 229

1. A Z, a z, Shift, Ctr, Alt


2. 0 9 +, -, *, /
3. F1 F12
4. , , ,
5. Esc, PrintScreen, Scrool Lock, Pause

Window
key Window
Start
(gaming
keyboard)

28/04/2010

10 of 229


(Serial Port) PS/2
USB (Wireless keyboard)

(Mouse)

GUI


(mouse pointer)

(Click)

(Dragging)


2 3 PS/2,
USB


(Output Unit)

28/04/2010

11 of 229

(Text)

(Graphics)
(Audio)
(Video)

(Output Devices)

(Monitor)
(soft copy)
(Monochrome)

CRT (Cathode Ray Tube)
(flat panel
display) (LCD)

LCD

LCD

(resolution), (size),
(dot pitch)

28/04/2010

12 of 229


1600 x 1200
1600 1200

Aspect

SVGA
XGA
SXGA
WXGA

Super Video Graphics Array


Extended Graphics Array
Super XGA
Wide XGA

UXGA
WSXGA
WUXGA
WQXGA

Ultra XGA
Wide Super XGA
Wide Ultra XGA
Wide Quad XGA

800 x 600
1024 x 768
1280 x 1024
1280 x 800 or
1366 x 768
1600 x 1200
1680 x 1050
1920 x 1200
2560 x 1600

Ratio
4:3
4:3
5:4
16 : 10 or
16 : 9
4:3
16 : 10
16 : 10
16 : 10

WXGA
1280 x 1024
19 21
(dit pitch) pixel pitch
0.28 mm


(hard copy)

Dot-Matrix
(Laser Printer)
(Inkjet Printer)

(Speaker)

(Sound Card)

28/04/2010

13 of 229

(Main Memory)



(Integrated circuit) (RAM) (ROM)

(RAM) Random Access Memory)



28/04/2010

14 of 229

2.

(ROM) (Read Only Memory)


()

ROM BIOS

(Byte) (kilobyte)
(Megabyte) (Gigabyte) (Terabyte)

kB
MB
GB
TB

1,024
1,048,576
1,073,741,825
1,099,511,627,776

(Secondary Memory)



(Harddisk), CD, DVD,
(Flash Memory)

1.44 MB

28/04/2010

15 of 229

Kilobyte (kB)
Megabyte(MB)
Gigabyte (GB)
Terabyte(TB)
Petabyte(PB)
Exabyte(EB)
Zettabyte(ZB)
Yottabyte(YB)

1
1
1
1
1000
1
1000
1

2 1,024
220 1,048,576
230
240
250
260
270
280
10

2.3


(Personal Computer)

PCCompatible IBM Apple
PC Windows
Apple Macintosh Mac OS

PC Windows

Apple

Mac OS

28/04/2010

16 of 229

(Notebook Computer)

Mobile Computer
PC
PC

Notebook
(Handheld Computer)

(Stylus)
mail
PDA (Personal Digital Assistant)
Pocket PC

Hand-held Stylus

28/04/2010

17 of 229

Server
PC

(Mainframe Computer)




(Supercomputer)

PC

28/04/2010

18 of 229

(Embedded Computer)



28/04/2010

19 of 229

1
. 1.
..2.
..3.
. 4. BIOS

. 5.
. 6.
. 7.
. 8.
. 9.
. 10.
2
1.
.
.
.
.
2.
.
.
. Flash Memory
.
3.
. (chip)
.
.
.
4.
. MiniComputer
. MicroComputer
. Embedded Computer
. Microprocessor
5.
.
.
.
.
6. Apple
. Mac OS
. Windows
. DOS
.
7.
.
.
.
.

28/04/2010

20 of 229

8.

.
.
9.
.
.
10.
. mobile computer
. notebook computer
. desktop personal computer
.

28/04/2010

.
.
.
.

21 of 229





(Machine Language)


(mnemonic)

(Assembly Language)
(High-level Language)

(Low-level Language)

2.1


0 1
(Machine Language)



5
(Machine Language)
.. 1952


61H (61 )
AL x86/IA-32

28/04/2010

22 of 229

10110000 01100001
(Assembly Language)
.. 1952
(Assembly Language)
(Mnemonic code)

x86/IA-32 61H
AL
1011000 01100001

MOV

AL , 61H


(Assembler)
MOV AL , 61H

(High-level Language)
.. 1960
(Third-generation Language)

BASIC, COBOL, FORTRAN C


C Test

#include <stdio.h>
main() {
printf( Test );
}

28/04/2010

23 of 229



(Very high-level Language)
4 (Fourth-generation Language)
4GLs
(Procedural Language)





SELECT First Name, Last Name
FROM Employees
WHERE City = Bangkok

COBOL




(Query Language)


SQL (Structured Query Language)
(Natural Language)
5 (Fifth generation Language)
5GLs

28/04/2010

24 of 229




(Knowledge base system)
SQL

SELECT First Name , Last Name
FROM Employees
WHERE City = BANGKON

TELL ME THE NAMES OF EMPLOYEES IN BANGKOK




(Source Program) (Source Code)

(Executable
Program)

(Assembler) 2.1

2.1


(Interpreter)

(Compiler)

2.2
28/04/2010

25 of 229

Interpreter

Compiler

2.2

2.2

(BASIC)

.. 1963 Dartmouth College


.. 1980 Basic Beginners Allpurpose
Symbolic Instruction Code

10 PRINT HELLO WIKIPEDIA!
20 GOTO 10

28/04/2010

26 of 229

(FORTRAN)

.. 1950 FORTRAN FORmular TRANslator








program HelloWorld
write (*,*) Hello, world!
end program HelloWorld

:

:

(COBOL)


.. 1960 Business Oriented Language
(Structure Program)

IDENTIFICATION DIVISION.
Program-Id. Hello-World.
*
ENVIRONMENT DIVISION.
*
DATA DIVISION.
*
PROCEDURE DIVISION.
Para1.
DISPLAY Hello, world..
*
Stop Run

28/04/2010

27 of 229

:

(OOP)
:

(PASCAL)

1970
Blaise Pascal
(Turbo Pascal)

Program HelloWorld(output);
Begin
Writeln(Hello, World!)
End.
:

(Bell Laboratory) .. 1970


(Unix)


#include stdio.h
int main(void)
{
printf(Hello, world\n);
return 0;
}

28/04/2010

28 of 229

:

:

(C++)


Class
(Object-oriented programming)

#include <iostream>
int main()
{
std::cout << Hello World! << std::endl;
return 0;
}
:

:

(VISUAL BASIC)

BASIC


28/04/2010

29 of 229

: GUI Windows

:

(JAVA)

.. 1990 Sun Microsystem



(Bytecode) Java Virtual
Machine

// Hello.java
public class Hello {
public static void main(String[] args) {
System.out.println(Hello, world!);
}
}
:

:





JAVA JAVA


JAVA
JAVA

28/04/2010

30 of 229



COBOL






Microsoft Access
Access
Visual Basic JAVA Visual Basic
Access



PDA

2.3










1.
2.
3.
4.

(Problem Definition and Problem Analysis)


(Pseudocoding)
(Programming)
(Program Testing and Debugging)

5. (Program Documentation and Maintenance)

28/04/2010

31 of 229






1.


2. (Input/Output Specification)




3. (Process Specification)

2.1 3

1.
1.1
1.2 0
2.
2.1
2.2 3
2.3
3.
3.1
3.2


2.3

28/04/2010

32 of 229


1
2
3

2.3



(Algorithm)


(Pseudo-code) (Flowchart)






(syntax)


(Bug)
(debug)

28/04/2010

33 of 229

1. Syntax Error
Coding Error
2. Logic Error



1. User Document User guide
2. Program Document Technical Reference

(Maintainance)

1
1.
. .
.
.
2.
. Basic
.
.
.
3.
. Basic
.
.
.
4.
.
. Window
28/04/2010

34 of 229

.
.
5.
.
.
. .
6.
. .OBJ
. .BAS
. .C
. .CPP
7.
.
.
.
.
8.
.
.
.
.
9.
.
.
.
.
10.

. bug
. syntax error
. logic error
. coding error
2

.1. 80486
.2.
.3.
.4. Windows
.5.
3
1.

28/04/2010

35 of 229

.
2.
.
.
3. (Assembler)
..
..
4.
..
...
5. (Source Code)
..
..
6.
..
..
7.
..
...
8.

28/04/2010

36 of 229

 3
 





   !"#$  %$& #


 ' ( ()#  &( 6 #$)#)  # #
 "%!&( " &+,-&  % '. ! /
0  1+)./ $2#3 $( 4 1  0 )./ ()"!5"//(
" +5!/(/( 0/() " &+53 !$&5#) /(6
).2.5&"!'&". . # !2 03#)  
.
"."!'/(3
". =
Hours * PayRate
&%5#)  % "!'&#
 03#)  
.
&"!'/(3


=
x 2 x "3

3.1 
 
 
#) $&!& 5#)/(& )1 () . 1$#)/(0  1+
&% . 1#)&%# !$ /.&%6 #) $

0  1+/( /.53/ ).2.#) !&
& # ()$& 
".
 # F  +". !".& //(." +5 (0  1+&
/( .5&F".3)+#/" +6/.5"!'/( 5&03#) /./(

4(6!$& #) /.


3'+
 
 !/(( !/(53 .5& .&%
4 $&(
#!/() 6/.5%. "4'  ' # ( %03 #) /.&
/./((
 /./(#)"!1
)#. G $&03  .5#$/(.) G !&

 " 4'  ' # ( "  ' (./

28/04/2010

37 of 229

1. 
  !
 ( $&0  1+53 .)! /." (" %  "
3'+4( "%
0.(
"
" 4   /.".)(,-&   53!/$2$($!"- G #
03
&

2. 
#$%&'
,4
 03$2 $!# $!0$3 203  /. %H(
" + )   # $& $2.)  (% "!"-

3. %
'%
()

.  0  ".$2.) % 6"


"4".$2.)$&/ 0 $
4#03$2  !/("4
 .)/ $4#03  ".$2.)$ !.
" . 3"

4. %
%
(+

)
 ,
''-%
 " 53 "$&-. I
I "

(3 (Module)
).) G  . )
.)  %$&03  "% 5#$ !/ .$&& 
)4"
)/(

5. 
!/ (
#3 !"- $6
/$" + # 50) .$+6 !$&("
)$%#" (O)##3 2.  /##3 ()/./(
4-   
#) /5
! )#3  ( " (O)3

6. '
'
 
%

,4
 " ) 1! )  ).(6 !$&/.5$2 /$
   /.2. .  6 " )/  .
6
/  /
$#) &%    +))
#)
 ).#  )#& ..    (Program Development Life Cycle:
PDLC)  
() 6 #(
1. #" &+" (Requirement Analysis & Feasibility Study)
2. # 0 /#,-& (Algorithm Design)
3. #(!#)  (Program Coding)
4. #(
/#  (Program Testing & Debugging)
5. ##) 
(Documentation)
6. #
!4   (Program Maintenance)

28/04/2010

38 of 229

" &+"
 0 /#,-&
#) 
(
/#
#) 

!4 

$!. G $ . # 


"53$& .. !
5(/ !&
$
'5&
.,-&
).(# 6)/
")!.
& 6/( !&
$# 5 !/  G 
$# 1 5 4  )6/(
1" +# $(! 2.)$&#) (!/).
 1O /(0  1+4.&)   . # 2.)$&(" 
)
$#) 
!$&)
) "("2( /.
 (".).#)&%   .$,4

 1)$&.(# 2. " )#) 254 .1" +)!
. ! ()i  ).)03 $&.
#)    2.)$& "(#  
 
)
/.


3.2 -  123'
$
-345-

" &+,-&&%" &+" !"#$,-& "&


 "%  () )(. 0  1+ / $2#3  / %$&/(0  1+
 #  0 )./

" )#. " &+,-&
&%" &+ " &+"# . #) 
5%.#!"-4( .5# 0 /#,-& (!#) 

28/04/2010

39 of 229

$" &+,-& (6 '# G (


 /
 1
).$&" +! $&! /()
#)# G 6/(
+ 4)./
 1
)5  ' #0  1+.)./  (
O ("%  + &%.) !  ()1
)
) )(() 2.5$& (O & )./  # (
)! &. ()./ 5& ("%  + 

(). $&  + #&&%/. .&&%)&%/.


#3 #)./
. 

& /(

. (0 /  ()%


3

#0  1+  (3.5&#3

 #3  4


")./ #3 .$(  0 /(+ 4


 $2
 %
. $2  / #3 !# &% ".)3.$ &.
  0  ( $2 (0  1+
1  0 )./
1
)5 !(
##  0 1 ,-& %$&/(0  1+
 () '.#3 . G 
#/ 6
$  
  O$(   0 # !
  G )./
 5&
  0 
#3 & )". 
#3 #/ ".   0 &%

#3 #/&(   0 #)"!1


)1  0 
#)# G $  ' #&) &%#)06/(
1  0  #)$  '  1( !(
""(
#  %$2$ ,-&!&
#)  () ( !(
##2"!'I
 #3 ###,-&!  '/0  1+ ()#. G #)#
   /"!#" +/(  1!/((3  /#,-& &
"!
/(4'

28/04/2010

40 of 229

%/(" &+,-&   (


(3() () F#3 #/
(3. ,-&/&%/.
 (%
6 3.1 #)  ,-&()" + !&
$&" +"!'&".
)2  ("."!'/(
$76)

 /

".#  . "
+ 4)./ + 4".41# O
#3 #
&  , 2%  , !2!6
$
2% Hours , ".)26
$ 2% PayRate
1  0
!&(1"!'
".41
=
!2 x .2
#  0
1. 
2. 
&  , 2%  , !2! , ".)2
3. "!'
".41
=
Hours x PayRate
4. (0  1+ &  2% ".41
5. 
!

28/04/2010

41 of 229

 (%
6 3.2 #)  ,-&()" +$&
 (
"."!'/(
$76)

 /
"!'#3

+ 4)./ ".
3

 #)O
#3 #
"3#
 (h) #
(r)
3

 #)
1  0
1"!'

 =
x 2 x "3
#  0
1. 
2. 
"."3 ".#

3. "!'".   = x r2 x h
4. (".
O
5. 
!

28/04/2010

42 of 229

 (%
6 3.3 #)  %)0 
# 2" + ()$& (" 
 (
$76)

 /
  +" 0 
(# 
+ 4)./ ("  (#  . "
#3 #
& !  (ID) ,2%name , " 

 O" (mid) , " 


).) (test) , " 
 )O"
(final)
1  0
1"!'
"  = "  O" + " 
).) + "  )O"
5 "  >= 80 /(( pAq
5 "  >= 70 <80 /(( pBq
5 "  >= 60 < 70 /(( pCq
5 "  >= 50 <60 /(( pDq
5"  < 50
/(( pFq
#  0
1. 
2. 
".  ID , name , mid , test , final
3. "!'"  (
Total = mid + final + test
5 Total >= 80 , Grade = pAq /# 4
5 Total >= 70 , Grade = pBq /# 4
5 Total >= 60 , Grade = pCq /# 4
5 Total >= 50 , Grade = pDq /# 4
5 Total < 50 , Grade = pFq
4. ( id , name , Total , Grade # 
5.  
/# 2  %
"
4" 5"
/# 6
6. &)4(!

28/04/2010

43 of 229

 (%
6 3.4 " &+,-& #) #
 #!"..#
(0 "%  +
$76)

#3 #
 #".$&)3.$2%  number1 , number2 number3
#3 + 4 0 $&2%  total
1  0
.". #!".

 #".
(0 # #
  5#)/((
Add_three_number
1. Read number1 , number2 , number3
2. total = number1 + number2 + number3
3. Printf total
END
 (%
6 3.5 " &+,-& #) !&
&".i )#4'&O3 ! ()
".
4'&O334( 4'&O3!4( #!6#/ $& (".4'&O3i )O
$76)

#3 #

".4'&O334()3.$ 2% max_temp
4'&O3!4()3.$ 2% min_temp
#3 + 4 ".4'O3i )O ()$2 2% avg_temp
1  0
1. 
".4'&O344( 4'&O3.4(
2. &".i )()() avg_temp = (max_temp + min_temp)/2
3. (". avg_temp O
 5#)/((
Find_average_temperature
1. READ max_temp , min_temp
2. avg_temp = (max_temp + min_temp) / 2
3. Output avg_temp to the screen
END
28/04/2010

44 of 229

3.3 $7
&
1  0 #   0  %$&/(0  1+3

 ()$2#3 !#


 . G /(!&(/  ##1  0  # )3.
1#)  ()/
)"!$  %  0 #3  2 1 "% 
#3  ".#/  0 
#3 #
/&(   0

 ,88
+% $36
(

1 
#3 ) #  0  (0  1+ ()
 F  +&%
/{ +
6/( & 6 
#3 )$&.  %!/  0 (0  1+ 2.%) G /.
&(#3   0 11 ( )$2()/ 2. $#)"  #)
&% ).  0 #)/(( 0O ./
  


  



 

!"#$"

  
 
#$"

 ,86 9-!' 9!(


1 
#3 &(6
$&.)"!.   0  (0  1+#4)
$" () 1 $2%& .)"!# #'  F#3 #/

28/04/2010

45 of 229

  


    " &
%



  %&

,,& 73 :188


$.#1  0  !&(3

 (0  1+().  ()./


51
#3 ().5&
# ".     ' $( &$21
#3 #&(
  0  
#3 )./ I3

(!(
1. '.3

#0  1+ & (Table Heading) &%/. 5  +&.


2. 5"!')(&( 2. )((%# 4" 6!&( &
 %6
".#)(/ . !&( ( . !&($&"..
3)+$
  2. sum = 0
3. '#3 !# (Input Data) &% # )# 5 #$2  '  )//.

 ."% "&.# #/. . 6$21


". !# 2. (%# 
#3  #"&.#"./. .  "% " (% 7500 " 9000 "
 13000 " 20000 /%) G I"."&.# #/..
!(
".

7500

9000

13000 20000 }}..

2.&. #"./. . /..


 ' #3 2. $2 #
". .5#3 )#

2.&.. 2.
!(
#3
".#3

28/04/2010

1
5

2
10

3
15

4
20

46 of 229

5
25

6
30

7
35

#3  ' ( .$21!&( $&" ..


". ##3 
#6 
#) $&!&(". 2. n =1 number = 5 
!&( 
#3 #.# 1 &%# 2 %/(!&( 
#3  #
./"%  0  +0  1+
4. $#) 
#3  )  !&(4(
#  0 &%(

.#3 &(&%) ()$21(


#3 4() &%$21 !&( !&


(Loop)
 %$&
 !
  0 . "
!"  () )(./


6!+,8+;!6
(
(
#3 4() 2 1 (
1.  %  #3 !# $(&".//./((
!(
#(

)3.5(
#3 ( (
.#3 #&(&%) !.  0
&(

. ". .
".//./(6    0 #3  )
2. $21!&(  1   %
"..#3 &(&%) 1 "!(
)3.& 6
 (0  1+$ . 
 "%#3 )4() 0.  0   &
 
.)4()6    0
'#) ()O 
".) G ./

)
+ 


-
(

10 INPUT X
20 IF X < 0 THEN GOTO 60


". # F  + 6
/$  X " 1 ".
5 #$  X ".(
$&!"!$
( 60 .5
/.$2.$&!"!$
( 30 ./
30 Y = X + 200
!".)3.$  X #' 

200 6
$  Y
40 PRINT X , Y
(".)3.$  X   Y
50 GOTO 10
) 
/!"!$
( 10 "% 
". # F  +
$&. 6
/$  X (".(53 ()".$&.)
60 PRINT pGOOD BYEq
5".
# F  + ".
6!"!$
( 60 
"% ("!. GOOD BYE
&
70 END
$&&)4(!
). O 
 "!$
( 20  $2!&
(
.#3 #&(&%) ()
(
.5&#3  #".
&)".#3 #"
 &(     ((/)
(
 60  %  +"!. pGOOD BYEq I
  !&
)../   & 
2%. LC  (

28/04/2010

47 of 229

)
+ 
10 INPUT X , LC
20 Y = X + 200
30 PRINT X , Y
40 IF LC = 1 THEN
GOTO 10
ELSE
GOTO 50
50 PRINT pGOOD BYEq
60 END


-
(

". ##6
$  X LC 5&".$ LC  1
(.#3 )/.&(
!".$  X

200 6
/$  Y
(0  1+". X Y O
5&".)3.$  LC  1 $&/!"!
 ( 10 .5
/.$2. $&/!"!
( 50 /

("!. pGOOD BYEq O



 

).% ! $&$.". #". ()". ".#3 6


/$  X .
".#3 (
6
$  LC ()5&".$  LC ". 1 &)".)/.$2.#3 
4() % !5
( 40  (
.".$  LC  1 $2.&%/. 5$2  ((/)

( 10  %
#3 "./

3.4
6!+,8 9$7
 45-

& /(" &+,-&  #4()"%#!&


(
.1 ,-&
/(#5$2/(&%/. I(
()#3 $2#3  4$
,-&())).#3  '&%' $&  ". $#. G
#  0  './("!
&%/. 5&"!
0( (  
/
/#.!(
#$(!/.53 $& 
/ /##!$&. (

# ,-&"(

#3 & ) G 24( 5&(

#3 24(() !
536/./(&)".#!

#!/().53 

$ . #"# (!$ . ##
  0 &(#0( (# /((3/(.).0( ($#$(

28/04/2010

48 of 229

 (%
6 3.6 
#1$ ,-&#)+$). 3.4
$76)
). 3.4    0 (
Add_three_number
1. Read number1 , number2 , number3
2. total = number1 + number2 + number3
3. Printf total
END


#1!/((
1.  #(
 4#24( ()$&24( ". 10,20 30  #24(
". 40,41 42
 
8;!
8;!6+
number1
10
40
number2
20
41
number3
30
42
2. "("!
#  0 ()
 
8;!
Total
60

8;!6+
123

3. # (!  . #()$& (".# 


  0 $ . #  !
  G
-
(8)
! ,
number1
number2
number3
Total
24( 1
1
10
20
30
2
60
3
Print
24( 2
1
40
41
42
2
123
3
Print

28/04/2010

49 of 229

4. 
0  1+## 2 # 3 (60 123) ./(0  1+
&%/.()(3  Total
 (%
6 3.7 5&  $&
#3  #!6 F  +! 9  $&


. #& .".  #
  #
 3)+ ()$& (0  1+O
$76)
,-&( .5" &+/((
+$6


! #
 
3)+
& 736
 (! # 
,
3)+O
8)
8


#3 # F  + 
 6'
$&
X  #
 # F  + 
num_p 
!

num_n 
!

num_z 
!3)+
$7
&
!&
,-& $&
 #3 # F  + ". ()1(
!&(1"(
5 #!
 $&
 1 #

!

5 #!
$&
 1 #

!

5 #3)+ $&


 1 #

!3)+
1  0
1. !&($&
num_p, num_n num_z ".3)+
2. .". # F  +6
$  X
3. 5././( /# 7
4. 5 X !
 $&
 1 
num_p /# 2
5. 5 X !
$&
 1 
num_n /# 2
6. 5 X ".3)+
$&
 1 
num_z /# 2
7.  +".
O 
8. &)4(

28/04/2010

50 of 229

!&
1  0 5&$# 6 ("!. p5 X ".3)+q / "!
6 /(.(
%5&0.# 4 5 /(6 (. #".3)+)3.  !&

1  0
5!/((
1. )).#3 # 1 24( 5& # 9 ". 13,7,-4,0,-5,2,6,-2 35
2. "("!
  0 ()  /(!
 5  !
3  3)+ 1 

 

8;!
5
3
1

num_p
num_n
num_z

3. 5&# % (#1  0  /((

-
(8)
! ,

 8 (X)

num_p

num_n

num_z

1
2
3
4
2
3
4
2
3
4
5
2
3
4
5
6
2
3
4
5
2
3
4
2
3

13
13
13
7
7
7
-4
-4
-4
-4
0
0
0
0
0
-5
-5
-5
-5
2
2
2
6
6

0
0
0
1
1
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
3
3
3

0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1

28/04/2010

51 of 229

-
(8)
! ,

 8 (X)

num_p

num_n

num_z

4
2
3
4
5
2
3
4
2
7

6
-2
-2
-2
-2
35
35
35
-

4
4
4
4
4
4
4
5
5
5

2
2
2
2
3
3
3
3
3
3

1
1
1
1
1
1
1
1
1
1

4. 
."!
$# 7  
"!
" (/ (.   0 53  I
5!/  .//(

% .$ .1 ,-&

#153(!#)   


#)#6
4(0( (2. 4(0( (# ). p
q (Bug) !&
(! /#
#0( ( ). p(
q (DeBug) !&
 !/./(54 "+ ).   Error
( Error #  2 &4& "%
1. 8&$! 
!6
 (
138/
:
(Syntax Error) #0( ((#)"("! (Source
Code) /.
/)'+ (Syntax) #  G #0( (#0( (.)4($&
/# %
$ &.  O   5#0( ( O)3.   O " +
 $&

).2. 5#) ()O " $&" +  +#"&()"!
WXRITLN(The Area is : ,my_area); %  O   " + 
/)'+#O 

."! WXRITLN /.)3.$O " ($
(" + (#0( ( O Syntax
Error $&&6
2. 8&$! 
!6 $!


-
(845-
&$!  (Logical Error) #0( ( (


 1$&!0(54 "+&%"  /##0( ( O !()


/ .  "! %&#0( ($&
2. 03#) !". A /

". B .
#)"%&)
6 !$&"." !'/(/.53 I5
#0( (()$2 #3 (

(Test Data) &%#3 


"!
$#
 (Execution Run) 5 53 0  1+/( 

"!

)3.. 

28/04/2010

52 of 229


  %&#0( (( .  !# (
1. 
.! #"%" + )1. pDesk Checkingq 1

. 5$&0  1+/(&%/. 
#0( (
()!&(#3 24(&#   ".# . G #) / .

().
 #"%" + 12. 2.) (#0( ( /(
 . . #"% ./
2. 
()"%" + %0.
$#   6. #"% 
" + #3 4 
"!
# "%" + ! Syntax Error
&%#0( (/)'+ 50("%" +  +#.#0( ( 5/(
"!

 
6".#$/(. . 53 %(
   5!
  
#3 #"%" +  %!  0 ./

3.5 ,,
8(  $3
$#) " +  ' #) )3.& )  ' I#

O " + %$2() 3

#) )$2(


8( ,,,%
 (Top-Down Programming)
 0#) 

(3 + !(


(),-& .
! 5&
(3 $("I
I6 $&
.(3  (3 ).) $&(3 & )(3 ).). G $2
!(
$

  #)". G   ' & )0%0 ()#)! . .


) !(
/ !"

#  " +


8( ,,!
3 (Modular Programming)
#)  )!. G  ).)#( 6& )   .
 ). (3 (Module) I5!/( (3 % G !$&5& "0( (6
5 /#(3 0( (/(.)# !&
$#)  (3 &  !&"
"4!
&( . )(3 $($2. (3 . (3 5)(3 ).) G /( . (3 
."
"4/)(3 % G /(()
#) $  ' (3  ).)  O"%  ).)O)$ (Internal
Subroutine)  ).)03#) #)# %.&# &  .5)$2/(
 O&"% ).)O) (External Subroutine) I ).)6
/$/
 (library) 
5)$2/( 5!/$2$% G /(

28/04/2010

53 of 229

(3  ).)

 & 

..

..

..
CALL
SUBPRO_A

SUBPRO_A

RETU
RN

3 & )(3  ).)


3 &6. &  &%(3 &  )(3  ).) %!(3
 ).)
    
! & ./ )(3  ).) 5
)$2/(& ) G " !&
#)  . O  "!!&
)(3
 ).) ./ (3  ).)6 "! %
. ).)
 

(3  ).)

 & 

(3  ).)


sun_B

..

..

..
CALL
SUBPRO_A

SUBPRO_A

CALL
sub_B

3 (3  ).)5)(3  ).)%

28/04/2010

54 of 229


8( $ ; (Object-Oriented Programming)
#)  $&.!. G 54 &%6 () 
.
6"% / $2! / % $2 65!6$2/( 
#(/(
 )/( $#)  !6. G  %!&
)$2$O)& 

28/04/2010

55 of 229

,,^_ - !6
(,6
6 1  %"!
534( )&#

1. #" &+,-&#$(03   51  0 


4(
. 
#. 3

 (0 + 4


".   0
.  ' ##3 #
2. #$#4()#" &+,-&
. !"#$
,-&
#. !"#$
 ' #3 #
". (
#1 ,-&
. (
3

#3 # #3 


3. #$("%"&)# 
. !"#$
,-&
#. 1
)#!# G
". "(1 ,-&
. (
#!
4. 5&$&" +"!'& %#& ) ."(.#3 $("%#3
 4
. % , "3
#. % , ")H
". ")H , "3
. % , ")H "3
5. #) " + #)#$(
. '#3  4
#. '#3 + 4
". 1
)1  0
. + 4

28/04/2010

56 of 229

6. (
"53##
 ,-&" !
#3 ).24(
. ).) 1 24(
#. ).) 2 24(
". #
 ' #,-&
. 4'5//($,-& G
7. #$("%" &++ 4
. " &+. !
"%4.$(
#. " &+.0  1+ /  0
". " &+3

  +0  1+
. 534#
8. ."(.  0 
#3 #/  0  ". & 
 O$(
. !&.)2O )+!(
#. 2%#)"
". !&.)"+/.!(
. 534#
9. &4$(2% $  0
. %  0 6
#3
#. -  '+$&#$.)$  0
". 5!/$2$##) /(
. 534#
10. 
#3 #/4)   0 ()& 
 O$(
. &".(%i )# 
#. 

)%"%&%#&4(
". 
 #3
4""
. 534#
6 2 !"%&) &#53 "%&) &#0(

.......1. #)"!1
)1  0 !$&52.)#) /(.)#
.......2. 5#3 # #   '2(# #().)&%!6
}}3. " &+,-& (3+ 4 
# 4(

.......4. 1  0 /."& )#
.......5.  '   +"%  + 5%.+ 4
28/04/2010

57 of 229

6 3 
"!5./
1. 
"&)#" &+,-&
...................................................................................................................................................
..................................................................................................................................................
.................................................................................................................................................
2. 
"&)#" &+3

##3  4 + 4


...............................................................................................................................................
..............................................................................................................................................
...............................................................................................................................................
..............................................................................................................................................
3. 5& "!'"#)"() /(!/ 20% O  7%
" &+,-& #)1  0 # G
..............................................................................................................................................
.............................................................................................................................................
.............................................................................................................................................
...........................................................................................................................................
..........................................................................................................................................
..............................................................................................................................................
..............................................................................................................................................
4. " &+,-&#"!' )".#4'&O3&.)I I)(Celsius)
&.){/+(Fahrenheit) ()5"!'/(3
F = (C x 9)/5 + 32
() F "%4'&O3$&.){/+
C "%4'&O3$&.)I 2)
(
!##1

28/04/2010

58 of 229



(Algorithm)

(Flowchart) 4
(Psudocodes)

5.1

(Algorithm)





(pseudo
code)



(Reserve Word)

Algorithm < >


1. .
2. .

END
28/04/2010

59 of 229

Algorithm
1. = 0
2. = 0
3. ()
4. 0

= +
3
5
5. =
6.
7.


Algorithm Avarage_Sum
1. count = 0
2. sum = 0
3. INPUT (value)
4. IF value > 0 THEN
count = count +1
sum = sum + value
GOTO 3
ELSE GOTO 5
5. avarage = sum / count
6. OUTPUT (avarage)
7. END
28/04/2010

60 of 229


1. X
2. Y
3. ARRAY = (X * Y)/2
4.


START

END

1.
2.
3.
4.

READ X
READ Y
Compute ARRAY = (X * Y)/2
Print ARRAY

5.2

28/04/2010

61 of 229

X = 4
4 X
X=Y+Z
Y Z
X
X = X+1
X 1





2 + 3 x 4 14 2 x 3 + 4
10

+
*
/
** ^

3
3
2
2
1








(Boolean)

28/04/2010

62 of 229


=
<
>
<=
>=
<>

5.1 1
A > 0 ( )
1
( )
2

A>0


A <> 0 ( )
2
( )
1

A <> 0

2
(True) (False)

28/04/2010

63 of 229

1 A
2 B
2

T
T
F
F

T
F
T
F

(A) AND (B)


T
F
F
F

(A) OR (B)
T
T
T
F

NOT (A)
F
F
T
T


AND



OR


NOT
5.2 2 AND
(X > 10) AND (X <= 15) ( )

1
( )
2

1
2 X 10
15
5.3 2 OR
(X > 50) OR (X <= 60) ( )
1
( )
2

28/04/2010

64 of 229

X 50 60

5.3

READ GET INPUT


(,) PRINT WRITE

READ VAR1, VAR2,..



INPUT VAR1, VAR2,

1,2, VAR Variable

READ X,Y

; X Y

Read student_name
Get system_date
Read number_1, number_2

; student_name
; system_date
; number_1,number_2

PRINT VAR1, VAR2,.


WRITE VAR1, VAR2,.
1,2,

28/04/2010

65 of 229

WRITE DATA1
PRINT A, B

; DATA1
; A B

Compute Calculate


Compute
ARRAT = (X * Y)/2
ARRAT X Y
Compute
Profit = Price Cost

INIT SET

INIT A, B : INTEGER
; A B
INIT Y
:REAL
; Y
SET A = 8
; A 8
5.4 7%
ComputeTotal
init total, price, vat : real
init vat = 0.07
read price
compute total = price + (price x 0.07)
print price, total
end

28/04/2010

66 of 229

\** total, price, vat


\** vat 0.07
\**
\** vat
\**
\**

5.4




IF IF-THEN-ELSE ENDIF
(Statement)

IF
THEN
;
1
;
ELSE
2
;
ENDIF
;

5.5 number 0
0

IF number > 0 THEN


PRINT POSITIVE NUMBER
ELSE
PRINT NEGATIVE NUMBER
ENDIF
number 0 POSITIVE
NUMBER NEGATIVE NUMBER
CASE , OF ENDCASE
CASE

CASE num OF
1 : PRINT 11111
2 : PRINT 22222
3 : PRINT 33333
ENDCASE
28/04/2010

67 of 229

10

num 1 11111 num 2


22222

5.5



1.
FOR , DO ENDFOR IN STEPS OF
IN STEPS OF

FOR
Statement
ENDFOR
2. REPEAT UNTIL
REPEAT
Statement_1
.
UNTIL (Condition)
3. WHILE - ENDWHILE

WHILE (Condition)
Statement_1
.
ENDWHILE
5.6 1 10 repeat-until
Print number 1 to 10
init num : integer
/** num
init num = 1
/** num 1
repeat
/** ( num = 10)
print num
/** num 1 - 10
increase num (num+1) /** num 1
until num > 10
/** num 10

28/04/2010

68 of 229

11

5.7 1 10 while
Print number 1 to 10
init num : integer
/** num
init num = 1
/** num 1
while (num <= 10)
/** num 10
print num
/** num 1 10
increase num (num + 1) /** num 1
endwhile
/**
5.8 1 + 2 + 3 + .+100
while 1
100

Sum_number_1_100
init i, sum : integer
/** i sum
init i = 0
/** i 0
init sum = 0
while (i <= 100)
/** i 100
compute sum = sum + i
/** i sum sum
compute i = i + 1
/** i
endwhile
print sum
/** sum

5.9 1 10 for
Number 1-10
init num : integer
/** num
for num = 1 to 10 do
/** num = 1 10
print num
/** num 1 - 10
endfor
/**

5.6

CALL

28/04/2010

69 of 229

12

CALL
LABEL
GOTO
START :

AB1:

Statement_1
..
.

GOTO AB1

END

1.
.
.
.
.
2.
.
.
.
.
3.
. READ
. FOR
. MEM
. CALL
4.

NUMBER

28/04/2010

70 of 229

13

INIT NUM : INTEGER


INIT NUM = 1
WHILE (NUM <= 100)
PRINT NUM
INCRAESE NUM
ENDWHILE

. 1 100
. 1 100
. 100
.
5. 5 INCRAESE NUM
. NUM
. NUM
. NUM NUM
.

2
1.

.
.
2.

.
.
..
.
3.

.
.
4. 10

28/04/2010

71 of 229





C++ C#

6.1

.c




(Integrated Development
Environment : IDE) DEV C++

C++

28/04/2010

72 of 229

DEV C++
1.


2. Editor Screen

File
New Source File Editor Screen
Untitled1
2. Source File
3.

1. File -> New


Editor Screen

28/04/2010

73 of 229

6.2

(C/C++)
5
1. (Preprocessor directives)
2. (Global declarations)
3. (The main() function)
4. (Uses-defined function)
5. (Program comments)


(Preprocessor directives)


(directive) #
(Header Part) Directive

#include
#include
#include stdio.h
#include Pro1.c

stdio.h
Pro1.c

#include <>

include main()

#define

28/04/2010


#define NAME VALUE

#define END 20
END 20
#define A 5*6+3
A 5*6+3

74 of 229

(Global declarations)

(main() function)

(Semi colon ;)
main() { }
main()

(Uses defined functions)


{ }

#include stdio.h
main()
{
function();
/* */
}
function()
/* function
{
return ;
/*
}

(Program comments)


/* */ //

C


28/04/2010

75 of 229

#include stdio.h
main()
{


}

1.


2. (Statement)
{ }
main

printf()

#include stdio.h
main()
{
printf(COMPUTER);
}

COMPUTER
printf() (string)
stdio
( standard input output) stdio.h
#include (directive) stdio.h (header file)
(comments)
/* */
/* PROGRAM BY TEERAWAT PRAKOBPHON */

28/04/2010

76 of 229

Dev-C++
1. File -> New ->Source File
2.

3. (Save) File -> Save


pro1 Save
2.

3.

1. File -> Save

28/04/2010

77 of 229

4. Save

4. pro1.cpp ( C++
cpp)

5. Execute ->Compile & Run


*/

1.

2.
1

28/04/2010

78 of 229


getch() conio.h
conio.h

6. printf
COMPUTER getch()



include

28/04/2010

79 of 229

6.3



stdio.h
#include

printf()
printf()
print format

printf()
printf( ,)
printf(control string,variable list,..);



variable list control string

6.1
/* PROGRAM BY TEERAWAT PRAKOBPHON */
#include stdio.h
main()
{
printf(COMPUTER\n);
\n
printf(\n\nCOMPUTER);
\n
printf(%d\n,20);
}
RUN
n (\n)
\n COMPUTER
(backslash)

28/04/2010

80 of 229


tab 8
hh

Backslash

\n
\t
\xhh
\a
\\

6.1 printf() 3 %d
(format code) % format specification


%d
%u
%f
%e
%c
%s
%%
%o
%x


(Char)
(string)
%

printf
printf(%s %d %f %c \n,Sam,14,-8.76,X);

variable list
variable list control
string
Sam 14 -8.760000 X
8.76
printf %
f

printf(%f %.3f %.2f %.1f,4.5678,4.5678,4.5678,4.5678);

28/04/2010

81 of 229


4.567800 4.568 4.57 4.6

scanf()
printf() ASCII
controlstring

scanf(control string,&variable list,..);


scanf(,&);

&
control string
int num;
/* num */

scanf(%d,&num);
Enter
num control string %d control string
printf()

int i,j;
/* i j */

scanf(%o %x,&i,&j);
printf(%o %x,i,j);
2
%o

char str[80];
printf(Enter a string : );
scanf(%s,str);
/* & */
printf(Here s your string: %s,str);

28/04/2010

82 of 229

str 80
str


RAM






ASCII Unicode


#include stdio.h
int
feet ,inches;
main()
{
feet = 6;
inches = feet * 12;
printf(Height in inches is %d ,inches)
}

Height in inches is 72

int feet inches
Integer () main()
feet 6
feet 12 inches printf
printf
(Comma)
%d

28/04/2010

83 of 229


63 63
1 ,
(,)

Data Type

, ..;
Variable Name, . ;

int

feet , inches;

Integer
-32767 +32767 ( )

A Z 0 9



(Reserved Word)
=

variable = expression;
expression
assignment (=)
(+) (-)
* div /

28/04/2010

84 of 229

int x;
x = 5;

/* x */
/* 5 x */

int x, y;
y = 3;
x = y + 5;

/* x y */
/* y 3 */
/* y 5 x */

printf
%

x = 7;
printf(%d,x);
printf(%d,x + 9);

7
16


yards = 8;
feet = yards * 3;
printf(%d yards is , yeads);
printf(%d feet , feet);

yards = 8;
feet = yards * 3;
printf(%d yards is \n,yeads);
printf(%d feet \n, feet);

8 yards is24 feet

8 yards is
24 feet


printf(Yes \n);
printf(No \n);

printf(Yes \n);
printf(\n);
printf(No \n);

28/04/2010

85 of 229

printf(Yes);
printf(No);

Yes
No

Yes

YesNo

No


#include stdio.h
int
nickels,dimes,TotCenter;
main()
{
nickels = 3;
dimes = 7;
TotCenter = (nickels * 5) + (dimes * 10);
printf(%d nickels and %d dimes \n,nickels,dimes);
printf(= %d cents \n,TotCenter);
}

3 nickels and 7 dimes


= 85 cents




4
- (simple type)
- (string type)
- (structure type)
- (pointer type)

28/04/2010

86 of 229


(ordinal type) (Real
Data Type)

(Integer Data Type)



8 1
0 255

char
unsigned char
signed char
int
unsigned int

-128 127
0 255
-128 .. 127
-2,147,483,648 .. 2,147,483,647
0 .. 4,294,967,296

1
1
1
4
4




int Turbo-C 2 -32768
+32767 DEV-C 4

127
char

(Character Data Type)


ASCII

ASCII
A,B,C
\n

28/04/2010

87 of 229

\t
\a

1 tab
Beep

(Boolean Data Type)


(True) (False)

1 1 0

(Real Data Type)




float
double
long double

3.4 x 10-38 3.4 x 1038

1.7 x 10-308.. 1.7 x 10+308


3.4 x 10-4032 .. 1.1 x 104032

8
10


(string type)


255
NULL (\0) COMPUTER 9

O M P

U T

\0

28/04/2010

88 of 229

nickels
3

Dimes
7

TotCentr
85



#include stdio.h
int
x;
main()
{
x = 6;
x = 8;
printf(X is %d,x);
}

x
6
8

x 6 8 x
x 8 printf 8

(=)
num1 =
5;

num2 =
14;
14
num1 =
num2;
printf(%d,num1);
14
printf(%d,num2);
num1 5 num2 14
num1 num2 num1
14


.
count = count +1 { count }
.
sum = sum + x { sum x x }
.
num = 3 * num { num 3 }

28/04/2010

89 of 229

6.4


int y;
/* y */
y = 5 * 3 + 2*2;
/* y */
printf(Output = %d ,y);
Output = 19

5 3 2 2
y

+
*
/
%
++
--

(Addition)
(Subtraction)
(Multiplication)
(Division)
(Modulus)
(Increment)
(Decrement)

6.2
#include stdio.h
#include conio.h
main()
{
int x,y;
x = 3;
y = 2;
printf(x + y = %d\n,x+y);
printf(x * y = %d\n,x*y);
printf(%d + %d = %d\n,x,y,x+y);
printf(5 + 3 = %d\n,5 + 3);
getch();
}

28/04/2010

90 of 229


y = x + 5;
y = x 2;
y = x * 3;
y = x / 2;
y = 5 % 3;
y++;
y--;

x y
x 3 y 2 printf()
%d printf()
DEV-C

1
2
3
4
5

()

++ , -
*, / , %

+,
=


y = 7+8*2
8 2 16 7 y 23

y = 5%2 + 14/3 6

1. 5 % 2 = 1
2. 14/3 = 4.66
3. 1 + 4.66 = 5.66

4. 5.66 6 = -0.33
y -0.33
28/04/2010

91 of 229

6.5




1. (Single Selection)
2. (Double Selection)

.
.



2 (true) (false)

( )
1 2

(Relation Operators)

28/04/2010

92 of 229

==
!=
<=
>=
>
<

(Equal)
(Not Equal)
(Less Than or Equal)
(Greater Than or Equal)
(Greater Than)
(Less Than)

6 == 3
6 != 3
6 <= 3
6 >= 3
6>3
6<3

(Logical Operator)

&&
||
!

(AND)
(OR)
(NOT)



(5 == 4 + 1) && (18 <= 6 * 4)

if

if()
{

}

28/04/2010

93 of 229


if (x >= 10) printf(A\n);
printf(B);
x

x = 12
A
B

x=8

x = 15
A
B

sc 80
100 A if

if((sc > 80) && (sc <= 100))


printf(A);
if-else if
else

if()
{
1;
}
else
{
2;
}
25
25
x

28/04/2010

94 of 229

1. x
2. x 25
2.1
3.

X > 25

X<0

X>0

28/04/2010

95 of 229

4 3


1.
2. X
3. X > 0
3.1

3.2 X < 0
3.2.1

3.2.1
4.


1
1. (7%2) + (8%5) % 10
. 3
. 4
. 5
. 6
2.
. >
. =
. >=
. !=
3. if
. m = 4.5
. x = = 8
. A > B
. C > D
4. x 20 30
. if((x >= 20) && (x <= 30))
. if((x >= 20) || (x <= 30))
. if(20 < x < 30)
. if((x <= 10) && (x >=20))
5.
.
.
28/04/2010

96 of 229

.
.
6. if else
.
.
.
.
7.
. do..while
. do..while for
. for
. for while

2
1.

2. if

3. +, -, *
%

28/04/2010

97 of 229

7

(Sequential Connection)


8.1

1. (Single Selection)
2. (Double Selection)


if()

else

if()
{
}

8.1


2 (true) (false)

28/04/2010

98 of 229


( )
1 2



3
,

8.1

Y
X > 10

READ A, B

X=X+5

X=A*B

WRITE X

8.1

28/04/2010

99 of 229




1. X > 10
1.1 A B
1.2 X A B

1.3 X X 5
1.4 X
2.

8.2

IF IF-THEN-ELSE ENDIF
IF THEN
ELST ENDIF
8.1

1. X > 10
1.1 A B
1.2 X A B

1.3 X X 5
1.4 X
2.

IF X > 10 THEN
READ A, B
X=A*B
ELSE
X = X + 5;
WRITE X
ENDIF



8.1

28/04/2010

100 of 229


IF X > 10 THEN
READ A, B
X=A*B
ELSE
X = X + 5;
WRITE X
ENDIF

#include stdio.h
#include conio.h
main()
{
int A, B, X;
printf(X = );
scanf(%d, &X);
if (X > 10)
{
scanf(%d,&A);
scanf*%d,&B);
X = A+B;
}
else
{
X = X+5;
printf(%d,X);
}
getch();
}

X 5
X 5 X X 10
X 12 IF
A B

8.1

0
-1

28/04/2010

101 of 229

8.2

#include <stdio.h>
#include <conio.h>
main()
{
int x;
printf(INPUT X : );
scanf(%d,&x);
if (x < 0)
x = x * -1;
printf(%d,x);
getch();
}

X<0

X = X * (-1)

8.2
8.2

A B

A B
A > B
A

28/04/2010

102 of 229


8.3

#include <stdio.h>
#include <conio.h>
main()
{
int A, B;
printf(INPUT A : );
scanf(%d,&A);
printf(INPUT B : );
scanf(%d,&B);
if (A > B)
printf( %d is larger, A);
else
printf(%d is larger , B);
getch();
}
8.3
8.3

80
A
70
B
60
C
50
D
50 F

28/04/2010

103 of 229


8.4

X >= 80

X >= 60

X >= 50

X >= 70

Grade = A

Grade = B

Grade = C

Grade = D
Grade = F

Grade

8.4


80
A
70 80
B
C
60 70
50 60
D
50
F
8.5

28/04/2010

104 of 229

#include <stdio.h>
#include <conio.h>
main()
{
int x;
char Grade;
printf(Input Score );
scanf(%d,&x);
if (x >= 80)
Grade = 'A';
if ((x >= 70)&&(X < 80))
Grade = 'B';
if ((x >= 60)&&(x < 70))
Grade = 'C';
if ((x >= 50)&&(X < 60))
Grade = 'D';
if (X < 50)
Grade = 'F';
printf(Grade = %c,Grade);
getch();
}

X >= 70
X<80

Grade = B

X >= 60
X<70

Grade = C

X >= 50
X<60

Grade = F

Grade

8.5

28/04/2010

Grade = A

X >= 80

105 of 229

Grade = D

8.3

IF

IF <Condition> THEN
< >
T
ELSE
< >
F
ENDIF

8.6
8.6 IF
ELSE

IF
8.2

40 1.5


(PayType), (Hours)


1.
2. 40
3. 40
= 40 + 1.5
4. 40
5.

28/04/2010

106 of 229

10

IF Hours > 40 THEN


Pay = Rate * (40 +1.5 *(Hours - 40))
ELSE
Pay = Rate * Hours

T
F

T
IF
Hours > 40

Pay = Rate *
(40 + 1.5 *
(Hours 40))

Pay =
Rate * Hours

8.7

IF
T

PayType = Hourly THEN


IF
Hours > 40 THEN
Pay = Rate * (40 + 1.5 * (Hours 40))
ELSE
Pay = Rate * Hours
ENDIF

ELSE
F

Pay = Salary
ENDIF

IF..THEN..ELSE
IF
8.8

28/04/2010

107 of 229

11

8.8

9.6
8.3

Age < 16
Age >= 16 Age <65
Age >= 65

Charge (%)
7
10
5

28/04/2010

108 of 229

12
A

IF
Age < 16

Charge = 7

IF Age < 16 THEN


Charge = 7
ENDIF
IF Age >= 16 AND Age < 65 THEN
Charge = 10
ENDIF
IF Age >= 65 THEN
Charge = 5
ENDIF

IF
Age >= 16
AND
Age < 65

Charge = 10

T
IF
Age >= 65
Charge = 5

8.9

IF
T

Age < 16 THEN


Charge = 7

ELSE
T
F
F

IF Age < 65 THEN


Charge = 10
ELSE
Charge = 5
ENDIF

ENDIF

28/04/2010

109 of 229

13

IF
8.10

8.10
8.3 65
3 3
2
8.3

1000

30
30

28/04/2010

600
400
200
800

60
40
20
80

110 of 229

14


30 1000

1000

Sex = F


400

age > 30



1400

1000

age > 30


200

sex = F



1200



X Y
X Y

28/04/2010

111 of 229

15

IF-THEN-ELSE-ENDIF
X 14 Y 20


Y X
X Y

14
20
20

20
20
20

20


X Y
Y X

14
14
14

20
14
14



TEMP


X TEMP
Y X
TEMP Y

28/04/2010

TEMP

14
14
20
20

20
20
20
14

14
14
14

112 of 229

16

X
swap
IF X < Y THEN
MOVE X TO TEMP
MOVE Y TO X
MOVE TEMP TO Y
ENDIF

8.4




(char_1, char_2, char_3)

swap (temp)

temp char_1
char_1 = char_2
char_2 = temp


1.
READ char_1, char_2, char_3
2.
IF char_1 > char_2 THEN
temp = char_1
char_1 = char_2
char_2 = temp
ENDIF
3.
IF char_2 > char_3 THEN
temp = char_2
char_2 = char_3
char_3 = temp
ENDIF

28/04/2010

113 of 229

17
4.

IF char_1 > char_2 THEN


temp = char_1
char_1 = char_2
char_2 = temp
ENDIF
5.
PRINT To The screen char_1, char_2, char_3

1.

char_1
char_2
char_3

K
B
G
2.

char_1
char_2
char_3

z
s
a

B
G
K

a
s
z

3.


1
2
3
4
5

1
2
3
4
5

char_1

char_2

char_3

k
b

B
K
G

z
s

S
Z
A
S

4. 3 2
28/04/2010

114 of 229

Temp

k
k

z
z

18

8.5 2

1. 5%
2. 2%






(Price), (choice),

1 5%
2

(Month) x (Price) x 2%

1.
2. (Price)
3. (Choice)
4. Choice = 1
4.1 = Price (Price *(5/100))

4.2 (Month)
4.3 = Price x Month x (2/100)
4.4 = (Price + ) / Month
5.
6.

28/04/2010

115 of 229

19

Price

Choice

Choice = 1

= Price (Price x (5/100) )


Month

= Price x (2/100) x Month

= (Price + )/Month

8.11 8.5

8.4
IF..THEN..ELSE
IF
CASE, OF ENDCASE 8.12

28/04/2010

116 of 229

20

NO case
CASE = ?
Case 1

Case3

Case 2

Case 4

8.12

(CASE) CASE CASE
CASE CASE

8.6

H
P
C
S




Commission

Rate
Sales Commission
Salary

CASE
1.

28/04/2010

CASE code
H
P

OF
:
:

Pay = Rate * Hours


Pay = Rate * Pieces

117 of 229

21
C
S
ENDCASE
2. EXIT

:
:

Pay = Commission
Pay = Salary

code
8.13

code

CASE of
code
= H

Pay = Rate *
Hours

= P

Pay = Rate *
Pieces

= C

Pay = Commission
* Sales

= S

Pay = Salary

8.13


switch .. case
switch (variable)
{
case constant_1 :
case constant_2 :
case constant_3 :
.
28/04/2010

statement;
break;
statement;
break;
statement;
break;
.
118 of 229

22

case constant_n : statement;


break;
default : statement;
}
switch variable case
statement switch break
statement default
case case
case int char

NOTE
switch 4
1. switch if switch
if
2. switch
3. switch
4. default

switch (year)
{
case 1 :
case

2:

case

3:

case

4:

default :

printf(Fershman\n);
break;
printf(Sophomore\n);
break;
printf(Junior \n);
break;
printf(Senior\n);
break;
printf(Nonmatriculated\n);

}
year 1 Freshman
3 Junior 1,2,3,4 Nonmatriculated
switch selector
default

28/04/2010

119 of 229

23

switch
case
case

selector = const 1

selector = const 2

selector = const 3

selector = const n

default

8.14 switch..case

num case switch
switch(num)
{
case 4
: ; break;
/* */
case 2.5
: ; break;
/* */
/* */
case m
: ; break;
case 2
: ; break;
/* */
default
:
}

28/04/2010

120 of 229

24

8.5

8.4

0
-1

8.15

#include stdio.h
#include conio.h
main()
{
printf(INPUT X : );
scanf(%d,&x);
if (x < 0)
x = x * -1;
printf(%d\n,x);
getch();
}

X<0

X = X * (-1)

8.15

28/04/2010

121 of 229

25

8.5
A B

A B
A > B
A

B

8.16

#include stdio.h
#include conio.h
main()
{
int A, B;
printf(INPUT A : );
scanf(%d,&A);
printf(INPUT B : );
scanf(%d,&B);
if (A > B)
printf(A, is larger)
else
printf(B, is larger);
getch();
}

8.16

28/04/2010

122 of 229

26

8.6

80
A
70
B
60
C
50
D
50 F

8.17

X >= 80

X >= 60

X >= 50

X >= 70

Grade = A

Grade = B

Grade = C

Grade = D
Grade = F

Grade

8.17

28/04/2010

123 of 229

27

80
A
70 80
B
60 70
C
50 60
D
50
F
8.18

#include <stdio.h>
#include <conio.h>
main()
{
int x;
char Grade;
printf(Input Score );
scanf(%d,&x);
if (x >= 80)
Grade = 'A';
if ((x >= 70)&&(X < 80))
Grade = 'B';
if ((x >= 60)&&(x < 70))
Grade = 'C';
if ((x >= 50)&&(X < 60))
Grade = 'D';
if (X < 50)
Grade = 'F';
printf(Grade = %c,Grade);
getch();
}

X >= 70
X<80

Grade = B

X >= 60
X<70

Grade = C

X >= 50
X<60

Grade = F

Grade

8.18
28/04/2010

Grade = A

X >= 80

124 of 229

Grade = D

28


1
1.
.
.
.
.
2.
.
.
.
.
3. IF ELSE
.
.
.
.
4.
.
.
.
.
5. IF

.
.
.
.
6.
. IF ,THEN,ELSE
. CASE
. IF,THEN
.

28/04/2010

125 of 229

29

7 10
START

READ A, B

N
A >= B

A=A+B

B=A*B

PRINT B

END

7.
.
.
.
.
8.
. B A B
. A A B
. B
.
9. A 3 B 2
.
. A 5
. 2
.

28/04/2010

126 of 229

30

10. 9
. 2
. 2
. 6
.

2
. 1.
. 2.
. 3.
. 4.
. 5.

3
1.

.
2.

X
Y
Y X
M X Y

M X Y
M

28/04/2010

127 of 229

31

3. 2 X 7 Y 3

4.


0 49 F
50 59 D
60 69 C
70 79 B
80 100 A

28/04/2010

128 of 229

9.1


3
A

1.
2.
3.

Instruction

Instruction

F
GoTo

9.1

IF
<Condition(s)>

28/04/2010

129 of 229


3 3

for




for (initialization; condition; increment or decrement)
{

}
initialization

condition

increment

decrement


int i;
/* I */
for ( i = 1; i <= 5; i++)
printf(%d ,i);
i 1 i 5
i I
1 2 3 4
5

do-while



do {

}while (condition)
condition

while


28/04/2010

130 of 229

while (condition)
{

}
condition

9.2


9.2

1 10
1.
2. X = 1
3. X 10
X
X
4.

9.2


10.2
28/04/2010

131 of 229

FOR, DO ENDFOR
FOR

ENDFOR
9.1 1
10
10

sum
I


sum = 0
I = 1
I 10
4.1 sum sum I I
4.2 I
5. sum
6.
1.
2.
3.
4.

9.3 9.1

28/04/2010

132 of 229

9.1 (Sum)
(I) sum
I I
10 10

9.1 0 100 10

(Max), (Min)
Max Mix
10
I 10
Max = 0 Min = 100
x
Max Min

x


1.
2. I = 1
3. Max = 0, Min = 100;
4. I 10
4.1 x
4.2 x Min
Min = x

4.3 x Max
Max = x
4.4 I
5. Max Min
6.

28/04/2010

133 of 229

I=0
Max = 0, Min = 100

I <= 10

X < Min

Min = X

X > Max

Max = X

Max,
Min

#include stdio.h
#include conio.h
main()
{
int I, X, Max, Min;
Max = 0;
Min = 100;
for(I = 1; I <= 10; I++)
{
printf(Input Num %d ,I);
scanf(%d,&X);
if (X < Min)
Min = X;
if (X > Max)
Max = X;
}
printf(Max = %d, Min = %d\n, Max, Min)
getch();
}

9.4 10

28/04/2010

134 of 229

10

9.3




REPEATUNTIL
DOUNTIL 9.5

REPEAT
.
.

UNTIL ()

9.5

28/04/2010

135 of 229

do..while

do
{

statement;
}while(condition);
do condition while

9.2

int counter = 1;
/* counter 1 */
do {
printf(%d ,counter);
}while(++counter <= 10); /* counter 10 */

1 counter
10

1 2 3 4 5 6 7 8 9 10

9.3 100
100

int num;
/* num */
do{
printf(Input Number );
scanf(%d,&num); /* num */
printf(/n);
/* */
}while(num > 100);
/* num 100 */

28/04/2010

136 of 229

9.2
0

0
(sum)
0
(x) sum
x 0


0
1.
start
2. sum 0
3. X
4. X 0
sum = 0
4.1 sum = sum + X
4.2 X
5. sum
INPUT X
6.

START

sum = sum + x

INIT SUM = 0
READ X
do
SUM = SUM + X
READ X
while (X !=0)
PRINT X

INPUT X

NO
X=0

YES

END
9.6 9.2

Display sum

STOP
28/04/2010

137 of 229

10


#include stdio.h
#include conio.h
main()
{
int x, sum;
sum = 0;
printf(INPUT DATA );
scanf(%d,&x);
do {
sum = sum + x;
printf(INPUT DATA );
scanf(%d,&x);
}while(x != 0);
printf(Sum = %d\n,sum);
getch();
}

0


9.4
0

28/04/2010

138 of 229

11

Sum
Counter
(Sum) (Counter)
9.7
START

1.START
2.Sum = 0
3.Counter = 0
4.READ Age
5 DO
Sum = Sum + Age
Counter = Counter+1
READ Age
WHILE Age != 0
6.Average = Sum/Counter
7.Print Average
8. STOP

Sum = 0

Counter = 0

Enter
Age

Sum = Sum+Age

T
Counter =
Counter+1

Enter
Age

Until
Age = 0
T

Average =
Sum/Counter

Print
Average

END

9.7
28/04/2010

139 of 229

12

9.4



WHILEENDWHILE
9.8
x 1 10

1.
2. x 0
3. x < 10
x
x
4.

F
While
<Condition>
T

Instruction

Instruction

9.8

9.5
(fahrenheit) (Celsius) 15

28/04/2010




15

140 of 229

13
c_temp = (f_temp 32)*(5/9)

c_temp

f_temp

temp_count


1.
2. temp_count
3. temp_count 15
3.1 f_temp
3.2 c_temp c_temp = (f_temp - 32) * 5/9
3.3 c_temp
3.4 temp_count
4.

1.
2.
3.
4.
5.
6.
7.
8.

START
INIT temp_count = 0
WHILE temp_count < 15
READ f_temp
c_temp = (f_temp 32) * 5/9
PRINT c_temp
temp_count = temp_count + 1
ENDWHILE
STOP



1. 32 50

f_temp

32

50

2.

c_temp

28/04/2010

10

141 of 229

14

3.

temp_count

1,2
3
4
5
6
7
3
4
5
6
7

WHILE

f_temp

c_temp


32
0

1

50
10

4. c_temp 3 2

28/04/2010

142 of 229

15

9.5



C=B

C=B

Instruction

IF
C <= E

Instruction

Instruction

C=C+S

Instruction

C=C+S

IF
C <= E
F

.
9.9

C , B , E S
.
. WHILE
REPEAT-UNTIL .

28/04/2010

143 of 229

16

Counter = Begin
REPEAT
Instruction
Instruction
Counter = Counter + S
UNTIL Counter > End

Counter = Begin

Instruction

Instruction

Counter = Counter + S

Counter > End


T

Counter = Begin
WHILE Counter <= End
Instruction
Instruction
ENDWHILE

Counter = Begin

T
Counter <=
End
F

Instruction

Instruction

Counter = Counter + S

28/04/2010

144 of 229

17




1.



WHILE

READ DATA
WHILE DATA !=
.
.
READ DATA
ENDWHILE

2.

WHILE FOR
9.5

9.6

200 asterisk (*)






200 *

= +
= *
=
> 200 *

28/04/2010

145 of 229

18


number1

number2

sum, product, average

WHILE

AND
IF *

1.
2. sum
3. Prompt
4. number1 number2
5. number1 number2
5.1 sum = number1 + number2
5.2 produce = number1 * number2
5.3 average = sum / 2
5.4 sum 200
5.4.1 sum, * ,product, average

5.4.2 sum, product, average


5.5 Prompt
5.6 number1 number2
6.


START
INIT sum = 0
Prompt for number1, number2
READ number1, number2
WHILE NOT(number1 = 0 AND number2 = 0)
sum = number1 + number2
product = number1*number2
average = sum/2
IF sum > 200 THEN
Display sum, *, product, average
ELSE
Display sum, product, average

28/04/2010

146 of 229

19

ENDIF
Prompt for number1, number2
READ number1, number2
ENDWHILE
STOP

9.7
S U S
, , , , (full-time :F/T)
(part-time : P/T) U


S Records
number

name

address

age

gender

attendance_pattern

U
Record



S



number, name address


S

28/04/2010

147 of 229

20

Print_student_records
Print STUDENT LIST heading
READ student record
WHILE more records exist
IF student record = S record THEN
Print student_number, name, address
ENDIF
READ student record
ENDWHILE
END
START

Print
heading

Read
student
record

More
Records?
T
T

F
Record = S?

STOP

Print
Student
details

Read
Student
record

9.10 9.7
28/04/2010

148 of 229

21

9.8 9.7
, ,
9.7



1 IF
Produce_part_time_female_list
Print PART TIME FEMALE STUDENTS heading
READ student record
WHILE more records
IF student record = S record THEN
IF attendance_pattern = P/T THEN
IF gender = female THEN
Print student_number, name,
address, age

ENDIF
ENDIF
ENDIF
READ student record
ENDWHILE
END

2 IF
Produce_part_time_female_list
Print PART TIME FEMALE STUDENTS heading
READ student record
WHILE more records
IF student record = S record THEN
IF (attendance_pattern = P/T
AND gender = female) THEN
Print student_number, name,
address, age

ENDIF
ENDIF
READ student record
ENDWHILE
END

28/04/2010

149 of 229

22

3 IF
Produce_part_time_female_list
Print PART TIME FEMALE STUDENTS heading
READ student record
WHILE more records
IF student record = S record
AND attendance_pattern = P/T
AND gender = female) THEN
Print student_number, name, address, age

ENDIF
READ student record
ENDWHILE

END

9.11 9.8
28/04/2010

150 of 229

23

9.9 9.8



total_students

total_selected_students




Produce_part_time_female_list
Print PART TIME FEMALE STUDENTS heading
Set total_students to zero
Set total_selected_students to zero
READ student record
WHILE records exist
IF student record = S record THEN
increment total_students
IF (attendance_pattern = P/T
AND gender = female) THEN
increment total_selected_students
Print student_number, name,
address, age

ENDIF
ENDIF
READ student record
ENDWHILE
Print total_students
Print total_selected_students
END

28/04/2010

151 of 229

24
START

Print
heading

Read
student
record

More
Records?
T
T

Print_total_
students

Record = S?

Increment
total_
students

Student
=P/T&female

Print_total_
Selected_
students

F
STOP

Increment
total_selected_
students

Print
Student
details

Read
Student
record

28/04/2010

152 of 229

25


1
1.
. 1
. 2
. 3
. 4
2.
. FOR
. REPEAT
. LOOP
. UNTIL
3.
.
.
.
.
4.
.
.
.
.
5.
.
.
.
.
6.
.
.
.
.
7.
. REPEAT.UNTIL
. WHILE.ENDWHILE
. UNTILGO
.
8.
.
.
.
.
9. REPEATUNTIL
.
.
.
.
10. WHILEENDWHILE
.
.
.
.

28/04/2010

153 of 229

26

3
1.

.
2.

I 0
I < 5
X
Y
Y X
M X Y

M X Y
I 1
M

3. 2 I

4. 10


5.
7 x 1
=
7
7 x 2
=
14
7 x 3
=
21

.
7 x 12
=
84
6. 5

28/04/2010

154 of 229

10





(array)



(element) (cell)
(index number)
8

X[1]
20

X[2]
35

X[3]
84

X[4]
21

X[5]
45

X[6]
65

X[7]
71

X[8]
39

X
[ ]
X[1..8] X[3]
X 3

X[2]
X[2] + X[3]
X[1+3]
X[5] + 1

2 35
2 3 35 + 84 119
4 21
5 1 46



X[5] :=
45;
45 X 5
Print X[6])
X 6

28/04/2010

155 of 229


0 1

10.1.

9 9
Age

7 Age(7)

1
2
3
4
5
6
7
8
9

Array
Age
12
9
11
12
9
14
13
8
16

Age(1)
Age(2)
Age(3)
Age(4)
Age(5)
Age(6)
Age(7)
Age(8)
Age(9)

28/04/2010

156 of 229

10

Fine_sum_10_number
Set sum to zero
FOR I = 1 TO 10 DO
READ x
sum = sum + x
ENDFOR
PRINT x
END

/** 10
/** x
/**
/**

10

x

10.1

array , Sum
number_of_elements

Find_sum_of_elements
Set sum to zero
FOR index = 1 to number_of_elements
sum = sum + array(index)
ENDFOR
Print sum
END

28/04/2010

/** sum 0
/**

157 of 229

10.2 10.1

Find_element_average
Set sum to zero
FOR index = 1 to number_of_elements
sum = sum + array(index)
ENDFOR
average = sum / number_of_elements
Print average
END

10.3

8


1 8

largest_element

Find_largest_element
Set largest_element to array(1)
FOR index = 2 to number_of_elements
IF array(index) > largest_element THEN
largest_element = array(index)
ENDIF
ENDFOR
Print largest_element
END

28/04/2010

158 of 229

10.4
10.3 smallest_element

Find_smallest_element
Set smallest_element to array(1)
FOR index = 2 to number_of_elements
IF array(index) < smallest_element THEN
smallest_element = array(index)
ENDIF
ENDFOR
Print smallest_element
END

10.5

10.4 10.5

Find_range_of_elements
Set smallest_element to array(1)
Set largest_element to array(1)
FOR index = 2 to number_of_elements
IF array(index) < smallest_element THEN
smallest_element = array(index)
ELSE
IF array(index) > largest_element THEN

largest_element = array(index)
ENDIF
ENDIF
ENDFOR
Print the range as smallest_element followed by largest_element
END

28/04/2010

159 of 229

10.2



A1
B1
C2
D2





A1
B1
C2
D2



C2
3

28/04/2010

160 of 229








month_table
Initialise_month_table
month_table(1) = January
month_table(2) = February
:
:
month_table(12) = December
END

10.6



, ,

ID

A001
A002
A003
B001
B002
ID
H
R
Total

28/04/2010

20
30
27
32
19



161 of 229

50
45
75
30
40

Total


Total H
R 100

FOR I = 1 TO 100 DO
Total(I) = H(i) x R(I)
ENDFOR

100
H R Total


Total

10.7

While
1

Read_values_into_array
Set max_num_elements to required value
/*
Set index to zero
Read first input value
WHILE (input values exist) AND (index < max_num_elements)
index = index + 1
array(index) = input value
/*
Read next input value
/*
ENDWHILE
IF (input values exit) AND index = max_num_elements THEN
Print Array size too small
ENDIF
END
28/04/2010

162 of 229

10.8 10.7 9999


WHILE 9999

Read_values_into_variable_array
Set max_num_elements to required value
Set index to zero
Read first input value
WHILE (input values NOT = 9999) AND (index < max_num_elements)
index = index + 1
array(index) = input value
/*
Read next input value
ENDWHILE
IF index < max_num_elements THEN
index = index + 1
array(index) = 9999
ELSE
Print Array size too small
ENDIF
END
9999


Write_values_of_array
FOR index = 1 to number_of_elements DO
Print array(index)
ENDFOR
END

28/04/2010

163 of 229

10

10.9
18

18
18

FOR
scores

Process_exam_scores
Set total_score to zero
FOR index = 1 to 18
Prompt operator for score
Get scores(index)
total_score = total_score+scores(index)
ENDFOR
Compute average_score = total_score / 18
FOR index = 1 to 18
Display scores(index)
ENDFOR
Display average_score
END

28/04/2010

164 of 229

11

10.9

28/04/2010

165 of 229

12

10.10 100 number


100 number

number

10.9


integer_total

integer_count
Process_integer_array
Set integer_total to zero
Set integer_count to zero

FOR index = 1 to 100


integer_total = integer_total + number(index)

ENDFOR
integer_average = integer_total / 100

FOR index = 1 to 100


IF number(index) > integer_average THEN
add 1 to integer_count
ENDIF
ENDFOR
Display integer_average, integer_count
END


28/04/2010

166 of 229

13

10.10

28/04/2010

167 of 229

14

10.3

1
[ ]
type
var_name[size]

[]
type var_name size
A
10
int A[10];
0
150 200
A
A[0] =
150;
A[9] =
200;
10.1 4

#include "stdio.h"
#include "conio.h"
main()
{
int A[4];
/* 4 */
int sum = 0;
/* */

printf("Input Number 1 : ");


scanf("%d",&A[0]);
printf("Input Number 2 : ");
scanf("%d",&A[1]);
printf("Input Number 3 : ");
scanf("%d",&A[2]);
printf("Input Number 4 : ");
4
scanf("%d",&A[3]);
sum = A[0] + A[1] + A[2] + A[3];
printf("Sum = %d\n",sum);
getch();
}

28/04/2010

168 of 229

15

scanf()

type array_name[size] = {value-list}


,
A 5

int A[5] = {1, 8, 4, 9, 7};



char A[3] = {A, B, C};
10.2 10

10.9

10

10



#include "stdio.h"
#include "conio.h"
main()
{
int number[10], i, sum = 0;
/* */
for(i = 0; i<10; i++)
{
10
printf("Input Number %d : ",i);
scanf("%d",&number[i]);
}
for(i = 0; i<10; i++)

sum = sum + number[i];


printf("The average is %.2f\n",sum/10.0); /* */
getch();
}

28/04/2010

169 of 229

16



10

#include "stdio.h"
#include "conio.h"
main()
{
int number[10], i, sum = 0;
for(i = 0; i<10; i++)
{
printf("Input Number %d : ",i);
scanf("%d",&number[i]);
sum = sum + number[i];
}
printf("The average is %.2f\n",sum/10.0);
getch();
}

2
2

2 4 4


2 2

28/04/2010

170 of 229

17

type array_name{Row] [ Column]

int AB[2][3]
AB 6 (2 x
3)
0
1

AB[0][0] , AB[0][1] , AB[0][2]


AB[1][0] , AB[1][1] , AB[1][2]

2
int sqr[3][3]
=
{
1 , 2 , 3,
4,5,6,
7,8,9
};
sqr 2 sqr[0][0]
1 sqr[0][1] 2 sqr[0][2] 3

10
1



5. 10.6

1.
2.
3.
4.

2
1. 10

2. 1
28/04/2010

171 of 229

18

3. A 20 20

4.
10,000
5 %
10 %
10,000 30,000
30,000
15 %


5. 40
3

6. 5

28/04/2010

172 of 229

1. 
 


( )


BCPL


B

Basic Combined
Programming
Language


PDP-7
(UNIX)
.. 2513


C
.. 2515
  ! 



  (SP2) / .. 

2. - ). )/012 34)5 6 7


# header
main( )
{
/* 
  */
declaration

 1 89:;.7 4 </=4> ? @ ( ) @( ;A


:1<. -A?;. ( )B  04); ? # C
# include <stdio.h>
@ 89:;.( <H=> stdio.h  @8<H=>1 /04B
 I:C. ( )4?J: <H=>1 :C.) <A.
;04 # define START 0
@ @( ;A  ):;.@8 Q START
-A?:;.    0
;04 # define temp 37
@ @( ;A:;. Q temp    @8 37

 1
 2

'''
( )  ) *

 3



  (SP2) / .. 



  (SP2) / .. 

28/04/2010

 3 Body 0434) -Q@ -A?B .4)


 .A.?H^)@>C
main ( ) Q=.: 04 ); ?@( ;A3483 
 .34) 
-Q@ 04 { ;=)B @1: ( );04H^)@>C  ) * -A?Q 
= ( );04H^)@>C1 * B .4)_AA.? 04); ? ;
 04 .4)@ B8-Q@ :;.: 04); ? } _A. ? C
main ( )
{
/* 
 .-Q@ */
( )  ) * ;
H^)@>C;
'''''
''''...
}
/* B8-Q@ */

 2 declaration @ @( ;AC


A3.4 J=B:C.:
-Q@ 7T) Q;043.4 J=  ) * 1B .4)IJ@
@ U(declare) :1@4 BT)B I( <:C.
:-Q@ <A. C
int stdno;
@ @( ;A Q stdno 3.4 J=C
AB(  W
;04 interger 7T)4 B<A.Q@  0,4,-1,-3,'.  .
float score;
@ @( ;A Q score 3.4 J=C
A=3 B9A
U
? (floating point)7T)4 B   0.23, 1.34, -21.002,  .


  (SP2) / .. 



  (SP2) / .. 

173 of 229

4? )-Q@
 04); ?  ) *

-Q@  1
# include <stdio.h>
int main (void )
{
printf(%Hello, Good morning. \n+);
}

{ } -  @( ;A3483 ;048=W4@34)H^)@>C


( ) - @ 89 b   ;044 >@
  >:;.@8H^)@>C
I. 5 ?:)=W8<  3.4  :A * QA) <   b 
  .4)@ 89( ;8H^)@>C1 *
/* */ - @ @( ;A comment ;043.4  < 
.4)@ :;. 4 </=4>c
8
)  7T)3.4  4?J
5 ?: 04); ?1BI04 < :C ( )c
8
) 


  (SP2) / .. 

" #$ %&'( Hello, Good morning.


7



  (SP2) / .. 

 !  2

&&' 2**)-$(1

# include <stdio.h>
main ( )
{
float point;
printf("\n\nPut your score in\n");
scanf("%f", &point);
printf("Your score is %f point\n\n", point);
}

" $)*)+,! -$( point


.*$/$0#$1.'  % Q 


  (SP2) / .. 


 ;=@@  A)1
1. .4)3T1 .A.? 4@6
2. ;. :C. 04); ? ) d
U  >:C04 Q
3.  I:C. 04 ); ? underline e_g <A.
4. ;. :C. reserved words C int, float, etc.
Note: 4 </=4>:5 6 7 I;W  Q @  )34)C04 
Q<A.? < @
 8 4@6 Q=C04 QBQ @  )@I. :C.
JQ8834) 4@6  )@
9



  (SP2) / .. 

Q883.4 J=Q=3 A



  (SP2) / .. 

10

-#0! 1.,(( /3*),-$(*&! +&&' 2*-,*) 


6789:;<=
Char
Int
Short
Long

Q883.4 J=;04C
A34) Q  ) * @( ;A<.:5 6 7
char
C
A34) 4@6;044@3
int
C
AB(  W @

short
C
AB(  W @

long
C
AB(  W    ?  2 
unsigned
C
A34)=3< 
A 04); ?
float
C
A=3 B9AU
?
double
C
A=3 B9AU
?  ?  2 

28/04/2010

Unsigned
Float
Double
11

7>;? @AB DC EFG HG(IGJK)


1
2
2
4

LMDJFN=9@A HG
 HGJFN;F Q ASCII I8: 1 JFNE>;UCD7N7JHVENMDW 0 YZW 255
LMDJFN=9VENMDW ]32768 YZW 32767
LMDJFN=9VENMDW ]32768 YZW 32767

LMDJFN=9
VDd 2000 =:D7
Unsigned short = 2 LMDJFN=9VENMDW 0 YZW 65535
Unsigned long = 4 LMDJFN=9VENMDW 0 YZW 4000 =:D7
4
I8:LDM JFN=9h CD=FW 10x 8h x ALDM VENMDW ]37 YZW +38
8
LNDY< J:;W9;WJFN=9UVALDM B<W9Z7?


  (SP2) / .. 

12

174 of 229

&' 2**)-$( $&)


1 4@3QA.? char -A?4?J5 ?: 04); ? e g C

:@ 3?-Q@ Q883.4 J=:C.BQ8)44@ 4 @=9 :;l


A)1

# include <stdio.h>
main ( )
{
char reply;

3.4 J=Q= QC


A4@3
3.4 J=Q= QC
AB(  W

reply = myn;
ooooooo

3.4 J=Q= QC


A=3 B9AU
?
}

3.4 J=Q= QQ88 


)


  (SP2) / .. 

13



  (SP2) / .. 

14

4? )-Q@

@ :;.  4@3;/
U6;04; 8 9

# include <stdio.h>
main ( )
{
char newline;

4@3;= 1<  I:;.  -A? ) Q B( <A.-A?@ :;. 


; ASCII 7T)B3?:J34)=32 QA -A?:C. 04); ?
e\g ( ;. ;04:C. 4@3@( ;A:;.@8;1 * 3?
 04); ? e\g ( ;8;8 )  C

newline = m\nn;
printf(%Hello, Good morning. %c+,newline);
printf(%Hello, Good morning.\n+);

; BELL QA.? ASCII 007 7T)@( ;A<A.A)1


beep = e\007g;
;04; 8 9 @ 3T18A:;  4@3@( ;A:;.@8;
04 n
 I@( ;A newline = e\ng;


  (SP2) / .. 

15



  (SP2) / .. 

&' 2**)-$( *& /4!

&' 2**)-$( /3(-+


B(  W :5 6 7 I:C.Q<A. 4 JQ88 04 int, short, long
Q= unsigned
( ;8@ @( ;A QQ88 unsigned 04B(  W < 
A
 04); ?1B .4):C. 8 J@8JQ883.4 J=B(  W C
A40
* 04 int ;04 short ;04 long 4? )C

( ;8=3 B9AU
? 1Q<A. 2 Q88 04 float Q=
double -A? double @W8  <A. 2  34) float
( ;8)  )
? U  > .4)@   =4?A:@ @W8 
@:C.@ @W8:JQ881 04@W8Q884W@-/7> A) 4? ) 4<1
=3
9,000,000,000
345,000
0.00063
0.00000924

unsigned int plusnum;


unsigned long width;
unsigned short absno; /* absolute number */


  (SP2) / .. 

28/04/2010

16

17

QA)Q88
? U  >
Q884W@-/7>
9
9.0*10
9.0e9
3.45*105
3.45e5
6.3e-4
6.3*10-4
9.24*10-6
9.24e-6


  (SP2) / .. 

18

175 of 229

  


@ @( ;A  :;. Q4 B( <A.-A?@( ;A:-Q@
;04@( ;A:3d @ @( ;AC
A@W<A. C
main ( )
{
int age = 18;
float height;

&' 2**)-$(#-
 
); ?IT) 4@3;= ? *  @48@3.4 
7T)@ ( Q;= ? *  @W8 @:5 6 71?@ 4?>
(array) A)13.4 J=Q88 
) 04 4?>34) 4@3 4)
 04); ?34)4?> 04 [ ] JQ88@ @( ;A 
)BT) 
=@6dA)1
char name[30];
; ?IT) Q name C
A char    ?  30 4@6
-A?@W8 4?> @ @W81B@W8?)@=<8 > Q=<8 >9A. ?
@W8; null 04 \0 A)1B@W8<A.B
)/?) 29 4@6


  (SP2) / .. 

height = 172.5;
printf(%Mr. Surasak is %d years old+,age);
printf(% and tall %f cms.\n+,height);
}

19



  (SP2) / .. 

4? )34)-Q@ :@ @( ;A  Q=)  b==/v>


# include <stdio.h>
main ( )
{
int sum,valuea;
int count = 1;

  printf( )  scanf( )


JQ8834) printf ( )
printf(  8 9 @ /
/>, 4 >@
  >, 4 >@
  >,...)
 8 9 @ /
/>  
) 3.4  Q=JQ8834)@ 
/
/>-A?4?J: 04); ? w x

valuea = 4;
sum = count + valuea;
printf(%Total value is %d.\n+,sum);

4 >@
  > B( 3.4 J= /
/> JQ88
@( ;A : 8 9 @ /
/>

}
b==/v>B @c3.4  : Total value is 5.


  (SP2) / .. 

JQ88:C.( ;8@( ;A@ /


/>:H^)@>C printf
%d /
/>A.?=32 
8
%o
x x =32 QA
%x
x x =32 
8;@
%u
x x =32 
8Q88< 
A 04); ?
%e
x x =3Q88
? U  > C 2.13e45
%f
x x =3 B9AU
?
%g
x x JQ88 %e ;04 %f -A?=04@Q88
19A
( ;8 
) JQ88@ /
/>A)1
%c /
/>A.? 4@6 A?
%s
x x3.
4 


  (SP2) / .. 

28/04/2010

20

21



  (SP2) / .. 

22

 04); ?( ;88=?JQ8834)3.4 J=


 04); ?=8 :;./
/>3.4 J=C
A3487. ?
(@
3.4 J=1); AB/
/>C
A3 )
 
) =3
89  @. )34)H_=A>
B9AU
?
@ @( ;A  @. )34)B9AU
?
Note @ 8=?JQ8834)3.4 J=1( <A.-A? @ :
 04); ?;= 1; ) 04); ? % Q= 04); ?
@( ;AJQ88@ /
/>
23



  (SP2) / .. 

24

176 of 229

JQ8834) scanf ( )

-%*)/%

scanf(  8 9 3.4 J=, 4 >@


  >, 4 >@
  >,...)

@ Q-44 4> ) d
U  >( ;85 6 7
+
@ 8@
@ =8
*
@  Jd
/
@ ; 
%
@ ; 4 U6 (- AJ=)

 8 9 3.4 J= @ @( ;AJQ883.4 J=: 04); ? w x


4 >@
  > B( 3.4 J= @W8(: Q) 7T)C
A34)3.4 J= .4)
) JQ88@( ;A: 8 9 3.4 J=
@ @( ;A=@6d4 >@
  > <A. 2 Q88A)1
I. 3.4 J=14 BB( <:C.:@  ( d
- B: 04 ); ? & ;. Q
I. 3.4 J=13.4  B( <@W8<.: Q=?
- < B(  .4): 04 ); ? & ;. Q


  (SP2) / .. 

25



  (SP2) / .. 

@ =?C
A34)3.4 J=

+,-
 
++n
- -n

( <A.-A?89C
A .4)@ =?5 ?: 04); ? ( )
Q=. );. Q;043.4 J= .4)@ =?Q=)C
A

int cost;
cost = 2.7+4.5;
cost = (int)2.7+(int)4.5;
27



  (SP2) / .. 

,. (Assignment expression)

point = 44;
; ?IT) @ @( ;A  :;.@8 Q point :;.    @8 44

3.4.6 +
-9,.+:9;+<:9;
> ;04 >= @@ ;04 @@  @8
< ;04 <=
.4?@ ;04 .4?@  @8
==
 @8
!=
<  @8

28/04/2010

28

( --,&.  = *) ==


.  = "-$(3.,
1&6)! .  == ".  !  -$(, ,

 04); ?:C.@( ;A  04 =


-A?@ @( ;A   )3 34) 04); ? :;.@8 Q4?J
 )7. ? C j = 7+2
;04
k = k+4



  (SP2) / .. 

/
  n 4@ 1
=A  n =) 1

 Q @  ); ) count++ Q= ++count


C
count = 5;
x = count++; B<A.  x  @8 5
Q=.  count  @8 6
count = 5;
x = ++count; B<A.  x  @8 6

float money;
.4)@ =? Q float < integer ( <A.A)1
(int) money;



  (SP2) / .. 

26

point == 44;
. 78 "-(/#(,, point ,!,$ 44 .: ,

29



  (SP2) / .. 

30

177 of 229


 if

+
-9,.+:9;+<:9;;; = 
&&
||
!

JQ8834) ( )
if ()04<3)
( ) .4)( I. )04<31B
);
4? )C
if (score >= 80)
grade = eAg; /* simple statement */
;04
if (math >= 60 && eng >= 55)
{ grade = eSg; /* compound statement */
printf(wYour grade is %c\nx,grade);
}


  (SP2) / .. 

Q= (and)
;04 (or)
<  (not)

 34)
/B>?8?8C
) @

/B> 1 && 
/B> 2 B
)  04
/B>1)4)B
)

/B> 1 | | 
/B> 2 B
)  04
/B>:A
/B>;T)
B
);04 1)4)
/B>1B
)
! 
/B>?8?8
B
)  04
/B>?8?8WB


  (SP2) / .. 

31


 if >.. else >..

+
-9,+=@<:
+:9;+<:9;+
AB ? :

JQ8834) ( )
if ( ( );04
/B>)04<3)
( ) .4)(  04)04<31B
)
else ( ) .4)(  04)04<31< B
)

JQ88<34) ( )?8?8)04<3 ? : A)1



/B> 1 ? 
/B> 2 : 
/B> 3
 ; ? 04
if 
/B> 1 B
)
( ( ):
/B> 2
else
( ( ):
/B> 3

4? )C
if (value1 > value2)
min = value2;
else
min = value1;


  (SP2) / .. 

C
33

34

4? )
switch (ch)
{
case m1n :
printf(%Red\n+);
case m2n :
printf(%Blue\n+);
case m3n :
printf(%Yellow\n+);
default :
printf(%White\n+);
}

JQ88 ( )
switch (
/B>)
{
case label1 : statement1;
case label2 : statement2;
'''''..
'''''..
default
: statementn;
}

28/04/2010

x = (y< 0) ? -y : y;


  (SP2) / .. 


 . ;+
AB9 E < : switch  break



  (SP2) / .. 

32

35



  (SP2) / .. 

36

178 of 229

3#$ loop .3#$( 03

4? )
switch (ch)
{
case m1n : printf(%Red\n+);
break;
case m2n : printf(%Blue\n+);
break;
case m3n : printf(%Yellow\n+);
break;
default : printf(%White\n+);
}


  (SP2) / .. 


J while
JQ88
while (
/B>)04<3)
{
( )=J;
''''
''''.
}
37



  (SP2) / .. 


J for

38


 ;;;<:
. ;+
AB<:  : do while

JQ88
for ( 
/B> 1 ; 
/B> 2 ; 
/B> 3 )
{
( )48;
''.
}
 ( ):C.:@  8 9 :;. @ 48 ( );= ? * 48
-A?
/B> 1 04@ @( ;A  
 .:;.@8 Q:C.:@ 48

/B> 2 @ ?8?8 @4B48I. )04<334)
/B>
B
)B @ ( )  ( )48 
/B> 3  ( ):@ 
@( ;A  B=?Q=)<:Q =48


  (SP2) / .. 

JQ88
do
statement;
while (
/B>)04<3);
C

39

40


 goto  labels
( ) goto @48A.? 2  04
-  ( ) goto  ( ):;.@-AA<?) ( Q;)@( ;A
-A?B@( ;AC04 ?@ label name
- C04 (label name)  @( ;A ( Q;) ( )B@-AA
<( ) 


 break
:C. 04 .4)@ :;.@ ( )  I;=9A44@B @=JQ=@-AA
<?) ( )4?J4@=J -A?<  .4) B48)04 <3:A *


 continue

3.4 ) ! ( )1I04 ( ) ;=@=?):@ 3?-Q@


Q I. B( ;04;=@=?)< <A. 1 BT)B:C. ( )1

:C. 04 .4)@ :;.@ ( ) 1 ?.4@=8<48:; 4@ 1)


7T) =@6d )3. @8 ( ) break



  (SP2) / .. 

num = 2;
do
{
num++;
printf(wNow no is %d\nx,num);
} while (num == 10)


  (SP2) / .. 

3#$(4  ; break, continue, goto *) labels

28/04/2010

compound statements

41



  (SP2) / .. 

42

179 of 229

 (Function)

4? )-Q@ :C. ( ) goto


#include<stdio.h>
main()
{ int sum,n;
for(n=1;n<10;n++)
if (n==5)
goto part1;
else printf(%%d\n+,n);
part1 : printf(%Interrupt with no. 5\n+);
}


  (SP2) / .. 

43



  (SP2) / .. 



yzW K6F7 (Functions)


@ 44@Q88-Q@ :5 6 7B4?J8/012 
34)@ 44@Q88- AJ= (Module Design) -A?@ Q8)
-Q@ 44@) ?4? * (;04- AJ=) Q =) ?4?
B( ) 4? ):A4? );T) 1 Q=<  B 3 A
:;lB@
< ) ?4?;= 1 04 ( <3?-Q@ :
5 6 7B@ 3?:=@6d34)H^)@>C

44

-Q@ /048@=34)B( 8B @bJ.:C.


Q=QA)b=@  ( d
 IQ8)@ ( ) ) ?4?<A.A)1
83.4 J= 2 B( B @bJ.:C.
8@=3 2 B( Q=.@W8b==/v>
QA)b==/v>34)@ ( ) 



  (SP2) / .. 

45



  (SP2) / .. 

 ()
B<A. -Q@ @48A.?H^)@>C 4 H^)@>C
04
H^)@>C;=@

31 4@ . )-Q@ A.?5 6 C


Source file
function compile
function
function

H^)@>C@ 83.4 J=
H^)@>C:@ 8@=3

Source file compile


function
function
function

H^)@>CQA)b==/v>


  (SP2) / .. 

28/04/2010

46

47

Object
file

link

link

Library file
link
Execute
file

Object
file



  (SP2) / .. 

48

180 of 229

4.1 JQ8834)H^)@>C
Q88 1

Q88 2

int , char , float , double =

void C04H^)@>C ( @ @ U Q )


{
@ @ U Q5 ?:H^)@>C;
( );
}

C
A3.4 J= 0  C04H^)@>C ( @ @ U Q )
{
@ @ U Q5 ?:H^)@>C ;
( );
return (  3.4 J= 4. )@ )  @=8);
}


  (SP2) / .. 

49



  (SP2) / .. 

4? ) 4.1 QA)@ ( ) 34)-Q@ @ 8@


=3B( B
) 2 B( 8B @bJ.:C.

double SumDouble ( double x, double y )


{
return ( x + y );
}
void PrintOut ( double x )
{
printf ( w\n Result of sum is : %.2fx, x );
}
51



  (SP2) / .. 

52

4.2 @ @ U-/-<34)H^)@>C

 4.1 ()


void main ( )
{
double a1, a2, sumVal;
a1 = InputDouble( );
a2 = InputDouble( );
sumVal = SumDouble ( a1, a2 );
PrintOut ( sumVal );
}


  (SP2) / .. 

28/04/2010

50

 4.1 ( 4)

#include <stdio.h>
double InputDouble ( )
{
double x;
printf ( w\nInput real value : w );
scanf ( w%.2f x, &x );
return ( x );
}


  (SP2) / .. 

JQ8834)H^)@>C ( 4)

@ @ U-- <


)B( :
5 6 704)B @5 6 75 6 :=@6d .4)
@ @ UH^)@>C @4B?@:C.H^)@>C 1
(Predefined Function)

53



  (SP2) / .. 

54

181 of 229

 4.2

B @ 4? ) 4.1 B;W H^)@>C main ( ) B4?J: .


H^)@>C40 *  @ ?@:C. =@6d 4. )
@ UH^)@>C  4. )@ ?@:C.@4B @?@:C.
H^)@>C1 Q ; @ .4)@ ?. ?H^)@>C main ( ) 3T1<
<.A. 8 B .4) @ @ U-- <34)H^)@>C
 .4)@ ?@:C.@4  4



  (SP2) / .. 

QA)@ ( ) 34)-Q@ @ 8@


=3B( B
) 2 B( 8 B @bJ.:C.
:=@6d @ @ U-- <

#include <stdio.h>
double InputDouble ( );
double SumDouble ( double , double );
void PrintOut ( double );

55



  (SP2) / .. 

56

 4.2 ()

B;W :-- <<  @ @ UC04 


Q
Q @ 3?534) Q<.5 ?:
@ C?:;. 4 </=4> I B48B( 
34) Q 534) Q 534)@  0
 5 ?:-Q@  @ ?@:C.) 
)  ) *
@?@8H^)@>C1IJ@ .4);04< 
4@B @1 
4 BBQ?@-- <<3?<.:4
 =JC<H=>@W
<A.CA?@

void main ( )
{
double a1, a2, sumVal;
a1 = InputDouble( );
a2 = InputDouble( );
sumVal = SumDouble ( a1, a2 );
PrintOut ( sumVal );
}


  (SP2) / .. 

57



  (SP2) / .. 

58



4.3 @ ?@:C.H^)@>C

a1 .4) C
A double 04)B @  B )
0@=8 B @H^)@>C C
A double

@ ?@:C.H^)@>C @  0  B:C.
JQ88A) 4<1

a1 = InputDouble ( );

 8 = H^)@>C (4 >@


  >)

:C. J@8-- <

double InputDouble ( );


  (SP2) / .. 

28/04/2010

59



  (SP2) / .. 

60

182 of 229

10





a1 Q= a2 .4) C


A double
/04:;. )@8C
A Q34)4 >@
 >
@ U:-- <

PrintOut( sumVal );
:C. J@8-- <

void PrintOut ( double );

sumVal = SumDouble (a1,a2 );


:C. J@8-- <

double InputDouble ( );
)1.'2'(,<=% $ 0: ,  ,


  (SP2) / .. 

61



  (SP2) / .. 

62

4.4 3483 ( Scope)


 04 @ ?@:C.) H^)@>CB @ B4)/01
;?  B( ( ;8 Q  .4):C.5 ?:
H^)@>C1 Q= 04
19A@ ( ) 34)H^)@>C
@WB @  0/01;?  B( 1@=8J
88 @ :C.)  QQ = B 3483
34)@ :C.) 3T14?J@8 ( Q;)@ U Q
1

@ ( ) 34)-Q@ 5 6 7B( ) 


H^)@>C main ( ) @4 4  04H^)@>C main ( )
?@:C.) H^)@>C40 @WB @ ) 4-=
(Control)  8 9 @ ( ) <?)H^)@>C 1 *
B@ BB8H^)@>C ;04/8 ( ) return



  (SP2) / .. 



63



  (SP2) / .. 

B @ 4? ) 4.1 Q= 4.2  I


QA)3483 @ ( ) <A.A) 1

main ( )

a1
a2
sumVal

 ()

main ( )

step1

a1 = InputDouble(
InputDouble( );

28/04/2010

a1
a2
sumVal

step2

a2 = InputDouble(
InputDouble( );

InputDouble ( ) x

InputDouble ( ) x


  (SP2) / .. 

64

65



  (SP2) / .. 

66

183 of 229

11

 ()

Step3

 ()

main ( )

sumVal=SumDouble(a1,a2)
sumVal=SumDouble(a1,a2)

main ( )

a1
a2
sumVal

PrintSum ( )

sumDouble ( ) x
y


  (SP2) / .. 

67

69



  (SP2) / .. 

QA)@ ( ) 34)-Q@ :=@6d


  Q-@=84= QA)3483 @ :C.
) 34) Q5 ?:-Q@
#include <stdio.h>
int x;
void func1 ( )
{
x = x + 10;
printf ( wfunc1 -> x : %d\nx, x );
}

 4.3

28/04/2010

PrintSum(sumVal);
PrintSum(sumVal);

68

4@B @1 I@ U Q<.5 ?4@H^)@>C


8
d
 34)-Q@ B?@ Q-@
Q-@
=84= (Global Variable) 7T) Q I
?@:C.  ( Q;):A * :-Q@ @W<A. ?@.:
@d @ @ U Q C 04A?@ Q-@
=84=5 ?:8=W4@;04H^)@>C

3483 @ ( ) 34) QQ = B@( ;A4?J


5 ?8=W4@34) ( )5 ?: 04); ?@@ ( { } ) ;04
@ @ U:C)34)@ @ UH^)@>C ?@ Q
;= 1 Q-= 4= (Local Variable)



  (SP2) / .. 

step4



  (SP2) / .. 

B;W Q x @ U:Q =31 4B


( ) 4?J5 ?:H^)@>C @ @ U   1 Q=:C.
/01:@ @W83.4 J= =@



  (SP2) / .. 

a1
a2
sumVal

70

 4.3 ()


void func2 ( int x )
{
x = x + 10;
printf ( wfunc2 -> x : %d\nx, x );
}
void func3 ( ) {
int x=0;
x = x + 10;
printf ( wfunc3 -> x : %d\nx, x );
}

71



  (SP2) / .. 

72

184 of 229

12

 4.3 ()

 4.3 ()

void main ( )
{
x = 10;
printf ( wmain (start) -> x : %d\nx, x );
func1 ( );
printf ( wmain (after func1) -> x : %d\nx, x );
func2 ( x );
printf ( wmain (after func2) -> x : %d\nx, x);
func3 ( );
printf ( wmain (after func3) -> x : %d\nx, x);
}


  (SP2) / .. 

>*!3
main (start) -> x : 10
func1 -> x : 20
main (after func1) -> x : 20
func2 -> x : 30
main (after func2) -> x : 20
func3 -> x : 10
main (after func3) -> x : 20
73



  (SP2) / .. 

74

5.1 LND<:@FNI
 AhN FG LWB:DW

9:;<= GG LWB:DW =Vh<7Ah7


(Structures and Unions)

(4,3)

(0,0)

ED J:;W D HG9:;<=U{8G7 7 L;;87@ UV


V ;GI
9:;<=
7 x =V y 
|79:;<=UCD7N7JH
V}@ int
V}@9:;<=@A
~6:I8: M
V}@9:;<= GG LWB:DW BDDY
V D
V}@
9:;<=@A~6:8FW7A?


  (SP2) / .. 

75



  (SP2) / .. 

@ @ U Q3.4 J=Q88- ). )

@ @ U53.4 J=Q88- ). )


struct point {
int x;
int y;
};

Q88 1 struct point {


int x;
int y;
} x, y , z;

Member

-9+ N =
-,O9 struct .
PA
..QR ;
<:
9JO9  struct  
<:
9JO9 struct
+:9 -=
QR 


  (SP2) / .. 

28/04/2010

76

-9+ N .+P
B  struct .= A-PA 
A--:=.A--S struct  R ;-A :

77



  (SP2) / .. 

78

185 of 229

13

Q88 2 struct point {


int x;
int y;
};
struct point x,y,z


  (SP2) / .. 

@ @( ;A  
 .:;.@8 Q3.4 J=Q88- ). )

@ 
@ U
Q883.4 J=
- ). )

struct point pt = {320,200};

@ 
@ U
Q
3.4 J=Q88
- ). )

@ 4. )IT) C
@5 ?: Q3.4 J=Q88- ). )

struct_name.member

79



  (SP2) / .. 

4? )

; ?; 9  C
@34)3.4 J=5 struct 4 BB
 Q5:A@W<A. 1)3.4 J=/012  Q=
53.4 J=40 * C 4 ?> Q=?)@ U 
Q34)3.4 J=5 struct <A.4@A.?

 04 .4)@ 4. )IT) C


@5 ?: struct
 4?J )@8B9A:A8Q@- 44A
B:C.
printf ( T%d, %dW, pt.x, pt.y );
;04; @ .4)@  ( d? )B ; )B @
B9A
 . (0, 0)  :A I:C.
double dist, sqrt (double);
dist =sqrt ((double)pt.x * pt.x +(double)pt.y * pt.y );


  (SP2) / .. 

struct rect {
struct point pt1;
struct point pt2;
};
struct rect screen;
int co_x;
co_x = screen.pt1.x


  (SP2) / .. 

28/04/2010

80

4? )
pt2
pt1
81

; @ .4)@ @W83.4 J=
34);=? A)J
 I( @ @ U
Q<A.A)1



  (SP2) / .. 

82

5.2 D HG9:;<= GG LWB:DW

@ @ U
Q883.4 J=
- ). )

@ @W83.4 J=Q88- ). )5 ?:;?  B( B


@W8 =( A8 @ @ U C
@34)3.4 J=1
-A?<3.4 J=Q88- ). )B@483T1B @
3.4 J=;= ? * C
A Q=3.4 J=Q =C
A @B @ 
B4)/01:C.) Q   )@
04)B @@ B4)/01 
;?  B( :88:;lBB4)Q 4AA
; A.? 2 ;04 4 =) 

@ @ U
Q3.4 J=
Q88- ). )
@ 4. )IT)
 C
@
83



  (SP2) / .. 

84

186 of 229

14

4? )

struct alignment {
int num1;
char ch;
int num2;
} example;

5.3 D~6:9:;<= GG LWB:DW FGyzW K6F7

member
num1 ch
0
2
Byte Offset

num2
3

@ ( ) 34) Q5- ). ) I( ) 


 ) * <A.CA?@8 Q40 * ?@.@ ?8?8
Q struct @8 Q struct 04)B @3.4 J=34) Q
struct B@W84?J: Q C
@34) struct @ 
?8?8BT) .4)( b  Q C
@34) struct
 1 @ :C.)  Q struct @8H^)@>C I( <A.
;= ?=@6d 1)@ :;.H^)@>C 0   struct @ )
4 @
 >:;.H^)@>C Q struct

B;W num2 B<  I:C./01


A@8 ch <A.
04)B @ num2 3.4 J=5=3B(  .4):C./01 
Q4AA; A.? 2 ;04 4 =)  ( :;.@
A )<  I
( :C.-?C><A. / 1@ @ U C
@34)
- ). )B b= 4@ :C./01:;?  B( A.?


  (SP2) / .. 

4? ) 5.1

85



  (SP2) / .. 

86

@ ?@:C.) H^)@>C

H^)@>C:C.:@ @( ;A  :;.@8 Q struct

struct rect screen;


struct point middle;
struct point makepoint ( int, int );
screen.pt1 = makepoint ( 0, 0 );
screen.pt2 = makepoint ( XMAX, YMAX );
middle = makepoint ((screen.pt1.x + screen.pt2.x) / 2,
(screen.pt1.y + screen.pt2.y) / 2 );

struct point makepoint ( int x, int y )


{
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}

-9+ N  9:R <:


<  ;+^J;;_


  (SP2) / .. 

87



  (SP2) / .. 

4? ) 5.2 H^)@>C@ 8@ x Q= y 34)B9A 2 B9A Q= 0

4? ) 5.3 H^)@>C@ ;  B9A4?J:/01;=? ;04< 

 b=34)@ 8@ struct

int pinrect ( struct point p, struct rect r )


{
return p.x >= r.pt1.x && p.x < r.pt2.x &&
p.y >= r.pt1.y && p.y < r.pt2.y;
}

struct point addpoint(struct point p1, struct point p2)


{
p1.x += p2.x;
p1.y += p2.y;
return p1;
}

-9+ N  9:R+^.N<:
;N 9J R<:
:
+:
9 A- _9.N R<:
:
+:
9-+^ ,+-< ; 
.N 9J R<:
:
+:
9-. 1  .N 9J  R<:

:
+:
9-. +^ 0

-9+ N  9:R ,+-<;; struct  ; 




  (SP2) / .. 

28/04/2010

88

89



  (SP2) / .. 

90

187 of 229

15

JFN6A? =V;DKhK
(Pointer and Array)
int i;

6.1 JFN6A? FG ;88B (Pointers and Address)


int i;
i = 10;
i

400
402
404

i = 10;

10

400
402
404

<
@A 6.1 D @79:;<=~7E7MNhLNDUCD9;WJFN

V}@>?7D7


  (SP2) / .. 

91



  (SP2) / .. 

92

6.2 D
V DJFN

V}@JFN6A?
p

10 i

10 i

@ @ U Q5/4?> 4>B:C. Unary Operator


* 7T) C04?@ Indirection ;04 Dereferencing Operator
-A?B .4)@ U534) Q/4?> 4>:;.
4A =.4)@8534) Q .4)@  (?@. 
Q/4?> 4>5 void
 IC<1 ?) Q
5:A@W<A.)

p 40 36
0 0
i

10 40
0

<
@A 6.2 D @79:;<=~7E7MNhLNDUCD9;WJFN

V}@JFN6A?


  (SP2) / .. 

93



  (SP2) / .. 

4? )

6.3 D CDE78LMD =V D;MD7LMDJFN



V}@JFN6A?

int *ip;
@ @ U Q ip :;. Q/4?> 4>
C1<?) Q5 int

@ @( ;A  :;.@8 Q/4?> 4>B@ 


@( ;AQ4AA34) Q  54A =.4)@8
534) Q/4?> 4> 1 -A?@ :C.
Unary Operator & -44 4>4 . )IT)
Q4AA34)44BW (Object) :A *

double *dp, atof(char *);


@ @ U Q dp  Q/4?> 4>C1
<?) Q5 double Q=@ UH^)@>C atof
/ 
 4> Q/4?> 4>5 char


  (SP2) / .. 

28/04/2010

94

95



  (SP2) / .. 

96

188 of 229

16

int
int
ip
y
*ip
y
ip
*ip
iq

x = 1, y = 2;
*ip, *iq;
= &x;
= *ip;
= 0;
= 5;
= &y;
= 3;
= ip;

<
@A 6.3 D CDE78LMD =V D;MD7LMDJFN
JFN6A?


  (SP2) / .. 

400

402

ip

400

iq

400

402

ip

500

iq

502

97



  (SP2) / .. 

400

402

500

ip

400

500

502

iq

ip = &x;



  (SP2) / .. 

400

402

y = *ip;



  (SP2) / .. 

*ip = 0;

400

402

400

500

400 500

ip

iq

502

iq

28/04/2010

98

502

99

ip



  (SP2) / .. 

int x = 1, y = 2;
int *ip, *iq;

101

100

y = 5;

502


  (SP2) / .. 

102

189 of 229

17

400

402

ip

402

500

iq

ip = &y;

400

402

402

500

iq

402

502



  (SP2) / .. 

402

402

iq



  (SP2) / .. 

04)B @5 6 7 @ )4 @
  >:;.@8H^)@>CQ88
By Value Q=H^)@>C  I 0  (return)  <A.
/?);T)  ; @ .4)@ :;.H^)@>C @ 
=?Q=)  Q= 0  @=8 ?)H^)@>C ?@:C.
@@ ;T)  B .4)( /4?> 4>3. C?

105



  (SP2) / .. 

4? )C ; @ .4)@ 3?H^)@>C/04=8 


34) Q 2  b==/v>  .4)@ <A.B @H^)@>C1B 
2  34) Q( @ =8  ; @4 >@
  > 
Qv A B<  IQ@.l
^ ; 1<A. BT) .4):C./4?>
 4>3. C? -A?@ )  Q4AA34) Q1) 2
:;.@8H^)@>CB=8  34) Q1) 2 b  ) Q
/4?> 4>4 >@
  >34)H^)@>C

28/04/2010

104

6.4 JFN6A? =V;DK N7@K9;WyzW K6F7


(Pointer and Function Arguments)

4? ) 6.1



  (SP2) / .. 

500
502

103

iq = ip;
ip

400

ip



  (SP2) / .. 

*ip = 3;

502

106

-Q@ 4? )@ =8  Q 2 


-A?b H^)@>C BQA)@ )
4 >@
  >:/4?> 4>

#include <stdio.h>
void swap (int *, int *);

107



  (SP2) / .. 

108

190 of 229

18

4? ) 6.1 ( 4)

4? ) 6.1 ( 4)

void main ( )
{
int x = 5, y = 10;
printf(wBefore swap : x = %dx, x, w, y = %d\nx, y);
swap ( &x, &y);
printf(wAfter swap : x = %dx, x, w, y = %d\nx, y);
}


  (SP2) / .. 

void swap (int *px, int *py)


{
int temp;
temp = *px;
*px = *py;
*py = temp;
}

109



  (SP2) / .. 

110

in main ( )
x
y

4 >@
 >5/4?> 4>BC?
:;.H^)@>C  I=?   :;.@8 Q)3.
<A. 04)B @4 >@
 >1 B@W8Q4AA
34) Q)3.  04 @ =?Q=) 
34)4 >@
 >b  Dereferencing Operator ( * )
 34) Q)3. BIJ@=?  /.4 @
:

in swap ( )
px
py
<
@A 6.4 B8WLNDBFF7K9;W DBMW;DK N7@K GG;h7KJ;K FGyzW K6F7



  (SP2) / .. 

111



  (SP2) / .. 

112

6.5 JFN6A? FG;DKhK (Pointer and Arrays)

)%%

4 >?>53.4 J=@W8C9A34)3.4 J=
5A?@ @:C.@8@ ( )  4. )( ) 
@8 QC
AA?@;= ?  @ ( ) 
; 04@ C Q34)@UT@6 5 ?:;.4)
20   . 4 >?>:5 6 7B( ;=@@ 34)
/4?> 4>3. :C. @ ( ) :A * 34)4 >?>
 I:C./4?> 4>3. Q

int table[10];
@ @( ;A4 >?>C04 table 4 >?>5
int   C
@1); A 10  1)Q  table[0], table[1],
table[2], ... , table[9]  C
@5 ?:4 >?>B
  0
 4 Q= C
@ 9A. ?B4?J ( Q;)34)3 A
@ U<.=8A.? 1



  (SP2) / .. 

28/04/2010

113



  (SP2) / .. 

114

191 of 229

19

'78#  1%%
table
table[0] table[1] table[2]

B:C.88AC-A?b  04 ); ? [ ] C


4. )IT) C
@  3 34)4 >?>A.? table[2]  .
@ :C.)  C
@34)4 >?> I:C.) <A.; 04
Q/012 <

table[9]

2!  6.5 #/3*&%%&


#   10 -$(


  (SP2) / .. 

115



  (SP2) / .. 

116

4? )

  I4. )IT) C
@9@ 5 ?:
4 >?>4? )4
 5 ?:3483 34)3 A
<A.@ U4 >?><. Q @ :C.4 >?> @B
@ 3. IT) C
@:=@6d<-A?:C.
Q5 int C?

sumThird = table[0] + table[1] + table[2];


table[0] = 5;
if ( a[0] > a[9] )
printf (wFirst is greater than last\nx );



  (SP2) / .. 

117



  (SP2) / .. 

4? )

#! -')($


:;. i, j, k  Q5 int

:5 6 7B<  @ @( ;A:;. B48


3483 34)4 >?> -Q@  4>B .4)/? ?
3?-Q@ @?3.4)@8 C
@34)4 >?>
5 ?:3483 @ U4 >?><. ; @ @ 4. )4
)
IT) C
@4 >?>4@3483 <A.89<. C
table[12] 
)<A. 40 @ <4 3.4 J=:/01 34)
;?  B( 4 BB@W8  34) Q 40 ;04
 40:A< 4 B AA <A.

for (int k = 0; k < 9; k++)


printf (wValue at %d = %d\nx, k+1, table[k]);
table[i + j] = 0;
table[7 table[j]] = j;



  (SP2) / .. 

28/04/2010

118

119



  (SP2) / .. 

120

192 of 229

20

4? ) 6.2 :;.4   34)B(  W 5 B( B @

 C
@34)4 >?>4 B53.4 J=
/012 :A * @W<A. ;044 B3.4 J=5
Enumeration C
#define TSIZE
10
#define NAMESIZE 20
#define ADDRSIZE 30
enum month { JAN, FEB, MAR, APR, MAY,
JUN, JUL, AUG, SEP, OCT,
NOV, DEC }

?>84>A Q=QA)b=:=( A8@=8@

# include <stdio.h>
#define SIZE 5
main ( ) {
int k;
int table[SIZE];
for (k = 0; k < SIZE; k++)
scanf (w%dx, &table[k]);
for (k = SIZE-1; k >= 0; k--)
printf (w%d\nx, table[k]);
}



  (SP2) / .. 

121



  (SP2) / .. 

122

6.6 D~6:JFN6A? FG;DKhK


typedef enum month Month;
int age[TSIZE];
float size[TSIZE+1];
Month date[8];
char name[NAMESIZE], address[ADDRSIZE];



  (SP2) / .. 

@ ( ) :A * 34)4 >?> I:C./4?> 4>3.


C? 7T)B( :;.   W:@ ( ) J)3T1 

4 >?> a Q=/4?> 4> pa A)1
int a[10];
int *pa;
@( ;A:;./4?> 4> pa C1<?)4 >?> a A.? ( )
pa = &a[0]; /* ;04:C. ( ) pa = a; */
pa B@W8  Q4AA
 .34)4 >?> a

123



  (SP2) / .. 

@ ( <:C.) B I4   4 >?>


b /4?> 4><A.A)1
x = *pa;
B@ @( ;A  :;. x    @8 a[0] @ 
=04<4    C
@ ( Q;)  ) * 34)4 >?>
b  )/4?> 4> I( <A.-A?@ /
 
/4?> 4>3T1 1 /04=04<?) ( Q;)IA<
;04/
  3T1 N /04=04 < N ( Q;)
;044 BB=A  /04=04 ( Q;)=)

pa
a
a[0]

a[1]

a[2]

a[9]

J 6.6 QA) C1C1<?)Q4AA


 .34)4 >?>


  (SP2) / .. 

28/04/2010

124

125



  (SP2) / .. 

126

193 of 229

21

pa

@d pa C14?J a[0] ( )


pa+1;
B@ 4. )IT)Q4AA34) a[1] ; @
pa+i @ 4. )IT)Q4AA a[i] ; @
.4)@ 4. )IT)3.4 J=5 ?:34) C
@34)
4 >?> ( Q;) a[i] B:C. *(pa+i)

pa+
1

pa+
2

a
a[0]

a[1]

a[2]

a[9]

J 6.7 QA)@ 4. )IT) ( Q;):4 >?>b   C1




  (SP2) / .. 

127



  (SP2) / .. 

@ ):;.8@ 1 ;048@ i ;04 =8 i ; 04


@ =04<?) C
@34)4 >?> ( Q;) .4)@ 
04)B @534)3.4 J=Q =534)4 >?> C
int, float, double Q=40 * 3 A34)3.4 J=  )@ (
:;.3 A34) C
@5 ?:4 >?>Q =5 3 A
Q @  )@A.? @ ):;.8@;04=8A.?B(  4. )@ 
1B @=<@( ;.  ( d ( Q;) .4)@ :;.
4A =.4)
@83.4 J=Q =5-A?4 - 



  (SP2) / .. 

4@B @1?)  I:C./4?> 4>Q4 >?>


@ 4. )-A?:C. a[i]  I:C. *(a+i) 04)B @9@ 1)
4. )IT) a[i] 5 6 7B( ;. Q=) *(a+i)
/ 1@ 3?:JQ88:A@W:;.b==/v>:@ 
( ) CA?@ Q=@ 4. )IT)Q4AA C
&a[i] B b= @8@ :C. a+i

129



  (SP2) / .. 

:=@6dA?@@ :C.) /4?> 4>@W I:C.


( ):=@6d4 >?>@<W A. C @ 4. )IT) *(pa+i)
 I3?A.? pa[i] @W<A.b=CA?@

)Q @  )@34)4 >?>Q=/4?> 4> 04 /4?>
 4> Q Q 4 >?>< :C Q 
:;. a 
4 >?>Q= pa /4?> 4> @ 4. )IT) pa = a ;04
pa++ B I 4 </=><A. Q B<  I:C. ( ) a =
pa ;04 a++ <A.


  (SP2) / .. 

28/04/2010

128

130

 04 @ )C0434)4 >?>:;.Q@H^)@>C B


@ ) ( Q;)Q4AA34) C
@ Q@
34)4 >?>:;.Q@H^)@>C A)1 / 
 4>:
H^)@>C1B Q5/4?> 4>

131



  (SP2) / .. 

132

194 of 229

22

4? ) 6.3 H^)@>C8/ 


 4>/4?> 4>
-A?4 >@
 >) 4 >?>

B;W s /4?> 4> :H^)@>CB @  B48


3.4 J=    @8 e\0g ;04<  Q= @ =04 ( Q;)
= 1  (8 3.4 J=   ? /
 3T1=1) -A?:C. s++
@ ?@:C.H^)@>C strlen  I( <A.;= ?=@6d
strlen (whello worldx);
/* string constant */
strlen (array);
/* char array[10] */
strlen (ptr);
/* char *ptr;
*/

int strlen (char *s)


{
int n;
for ( n = 0; *s != e\0g; s++ )
n++;
return n;
}


  (SP2) / .. 

133



  (SP2) / .. 

134

4? )
4@B @1?) 4 BB@ U/ 
 4>5 ?:
H^)@>C strlen <A.: 2 =@6d 04 char *s Q88:
4? ) ;044 BB:C. char s[
s[ ] @W<A. -A?<B
:C.:=@6dQ@ / C?:J.<A.   s  
Q/4?> 4> Q=?) I):A34)
4 >?>:;.Q@H^)@>C@W<A. -A?< B(  .4)) C
@
Q@@W<A.C@

f (&a[2])
;04 f (a+2)
@ )Q4AA34) C
@ a[2] :;.@8
H^)@>C f @ @ UH^)@>C f  I( <A.-A?
@ @ U
f (int arr[ ]) { ......... }
;04 f (int *arr) { ............ }



  (SP2) / .. 



  (SP2) / .. 

135

136

6.7 DLCD7Nd FG ;88B


p < q
BB
) 04 p C1< C
@4?J@4 ;.  C
@
 q C14?J @ ?8?8:=@6dB:C.<A.
4 04 p Q= q C1<4 >?>A?@ 1
4@B @1?)  I:C.@ =8;04@ 8@
@8/4?> 4><A.CA?@ Q 
) ) 04
@ ( C1B .4)4?J:3483 3 A34)
4 >?> 1

:;. p /4?> 4>C1<?)4 >?>:A * ( ) p++


@ =04 p <?) C
@IA< Q= ( ) p += i
@ =04/4?> 4>< i ( Q;)B @ ( Q;)
^BB98 4@B @1?) I:C. 04 ); ?
  /v> (Relational Operator) C ==, !=, <, >=
Q=40 * ( )  @8/4?> 4><A. 
:;. p
Q= q C1<?) C
@34)4 >?>A?@


  (SP2) / .. 

28/04/2010

137



  (SP2) / .. 

138

195 of 229

23

4? ) 6.3 H^)@>C strlen( ) 89):;.@C83T1


04)B @ s C14?J ( Q;)
 .
-A?  p C1< s CA?@ Q B @ =04
p <=;T) ( Q;) B@   ( Q;) p
C14?JB @8 e\0g  04( p  9A. ? =8@8
s  ( Q;)
 .@WB<A.  ? 34)3.4 J=
)3.

int strlen (char *s)


{
char *p = s;
while (*p != e\0g)
p++;
return p-s;
}


  (SP2) / .. 

139



  (SP2) / .. 

4? )

6.8 JFN6A?JFN;F Q =VyzW K6F7


(Character Pointer and Function)

wI am a stringx
 04 @ :C.  ) 
)B @ /01 :;?  B(
 @8  ? 34)  ) 
)8@A.? 1 04)B @
=@6d@ @W83.4 J=53.4  :
;?  B( B @  4@6 null ;04 e\0g 4. ?
 4/04:;.J. B9A
19A34)3.4 J= @ B4)/01
A)@= B; 04@ B4)/0134)3.4 J=5
4 >?> 4 >?>34) char

@ ( ) @83.4  ;04?@  


)
(String) @ :C.3.4 J= 4@6;= ? * 
;044 >?>34)3.4 J=5 char ;044 BB
:C./4?> 4>C1<?)3.4 J=5 char @ 
( ) @8  ) 
) (String Constant)  I
3?5 ?: 04) w x


  (SP2) / .. 

a m

141



  (SP2) / .. 

2!  6.8 #/3*+&' 2*)!


#-1.,(( /3

28/04/2010

142

 ) 
)/8;W<A. 4<A.Q@3.4 
:C.:H^)@>C printf ( ) C
printf ( wHello, world\nx );
H^)@>C printf ( ) B8/ 
 4>
/4?> 4>C1<?)Q4AA34)3.4 J= ( Q;)

 .34)4 >?> Q=( 3.4  1QA)44@
 )49@d>QA)3.4 J= 2 

\0

s t r i n g



  (SP2) / .. 

140

143



  (SP2) / .. 

144

196 of 229

24

:@ 3?-Q@ B I:C./4?>


 4>C1<  ) 
):A * @W<A. C
char *pmessage = wHello, worldx;
pmessage B/4?> 4>5 char
C1<4 >?>34) 4@6 BQ @  )B @@ :C.
4 >?><C
char amessage[ ] = wHello, worldx;


  (SP2) / .. 

=@6d34)4 >?>C amessage B 


@ B4)/01:C.@84 >?>3 A 13 4@6
 1) null =@6d34)/4?> 4>C1<?)
 ) 
) B @ B4)/01:;.@8  ) 
)
3 A 13 4@6CA?@ Q B @ B4)
/01:;.@8/4?> 4>Q=( @ C1/4?> 4>1
<?)/0134)  ) 
)B4)4 <.

145



  (SP2) / .. 

4? ) 6.5 H^)@>C strcpy ( ) ( ;.  ( 


3.4  B @ Q;T)<?)4@ 
Q;T)3?:=@6d4 >?>
void strcpy ( char *s, char *t )
{
int i=0;
while ( ( s[i] = t[i] ) != e\0g )
i++;
}

pmessage
H e l l

o ,

w o r l

\0

amessage H e l l

o ,

w o r l

\0

J 6.9 @ B4)/01:;.@84 >?>Q= C1C1<?)  ) 


)


  (SP2) / .. 

147



  (SP2) / .. 

4? ) 6.6

H^)@>C strcpy ( ) 3?:=@6d


/4?> 4>
void strcpy ( char *s, char *t )
{
while ( ( *s = *t ) != e\0g ) {
s++;
t++;
}
}


  (SP2) / .. 

28/04/2010

146

4? ) 6.7

148

H^)@>C strcpy ( ) 3?:=@6d


/4?> 4>Q881

void strcpy ( char *s, char *t )


{
while ( ( *s++ = *t++ ) != e\0g ) ;
}

149



  (SP2) / .. 

150

197 of 229

25

4? )

@ @ U QC1 (pointer) C1<?) struct

struct point origin, *pp;


pp = &original;
printf ( %origin is (%d, %d)\n+, (*pp).x, (*pp).y );

@d@ )4 @
 > Q s t r u c t B< ; @8 s t r u c t
 3 A:;l 04)B @9@ 1)) Q struct B@ ( 
Q :; 3T1 :H^)@>C 7T)B( :;.C. Q==04)/01;?
 B(  B:C./4?> 4>3. C?Q@.^l; 1
-A?)Q4AA34) Q struct ?)H^)@>C7T)84 @
 >
/4?> 4> 4 @
 >BC1<?)Q4AA
 .34)
Q struct BC?:;.@ ( ) W3T1Q==04);?  B(
.4?=) Q 
) .4)) 04; @ @ =?Q=)  4 @
 >
/4?> 4>C14?J  : Q struct ) ?)H^)@>CB=?
-A?4 - 



  (SP2) / .. 

B<A. Q pp C1<?)3.4 J=Q88- ). )C04 struct


point @ 3? *pp B@ 4. )IT)- ). )

@ 4. )IT) C
@ I( <A.-A?4. )
(*pp).x ;04 (*pp).y

151



  (SP2) / .. 

@ 4. )IT) C
@4 B3?4@=@6d;T)-A?:C.
 04); ? -> 
p /4?> 4> JQ88
@ :C.A)1
p->member-of-structure
B IQ=)-? @ :C./4?> 4>
4. ) C
@34) struct B @ 4? )3. )8<A.
printf ( worigin is (%d, %d)\nx, pp->x, pp->y);

; ?; 9 
) .4)) 04 (*pp).x B< 
; 04@8 *pp.x 04)B @ 04); ? . B
=( A8  ( lJ)@ * ( B@ Q=
 ; ? *pp.x B; 04@8@ 4. )
*(pp.x) 7T)B( :;.@
A  b
A/= A3T1



  (SP2) / .. 

153



  (SP2) / .. 

4? )

28/04/2010

154

6.9 JFN6A? (pointer) 6A?I


hFW LWB:DW
(pointer to structures)

; @ /4?> 4>C1<?) struct rect A)1


struct rect r, *rp = r;
@ 4. )IT) C
@ 4<1B b= @8@ 4. )IT)
 C
@ A?@
r.pt1.x
rp->pt1.x
(r.pt1).x
(rp->pt1).x


  (SP2) / .. 

152

/4?> 4> Q@W8Q4AA34) 


Q40  I:C.C1<?)3.4 J=5:A *
@ :C./4?> 4>C1<?)- ). ) I( <A.
A)1

155



  (SP2) / .. 

156

198 of 229

26

Q88 1

typedef struct {
int day;
int month;
int year;
} Date;
Date today;
Date *ptrdate;


  (SP2) / .. 

Q88 3

typedef struct {
int day;
int month;
int year;
} Date;
typedef Date *PtrDate;
PtrDate ptrdate;


  (SP2) / .. 

Q88 2

@ @ U
Q883.4 J=
- ). )

struct date {
int day;
int month;
int year;
} *ptrdate;

@ @ U
Q3.4 J=
Q88- ). )
@ @ U 
Q pointer C1<
?) - ). )
157



  (SP2) / .. 

@ @ U
Q883.4 J=
- ). )

@ @ U5
Q pointer C1<?)
- ). )
@ @ U 
Q pointer C1<
?) - ). )

@ @ U Q ptrdate )1 3 =@6d


B I:C.) <A.; 04@1); A
; @ .4)@ :;. ptrdate C1<?) Q
- ). ) I( <A.A)1
ptrdate = &today;

159



  (SP2) / .. 

4? ) 6.8
@ 4. )IT) C
@34)- ). )b  Q/4?> 4>
ptrdate->day = 7;
if ( ptrdate->day == 31 && ptrdate->month == 12 ) .....
scanf ( w%dx, &ptrdate->year );

28/04/2010

160

-Q@ 4? )@ :C. C1 (pointer) C1<


?)- ). )

#include <stdio.h>
struct date { /*date template */
int day;
int month;
int year;
};
typedef struct date Date;
typedef Date *PtrDate;

@ 4. )IT) C
@- ). )-A?:C. 04 ); ? ->
(*ptrdate).day = 7;
if ( (*ptrdate).day == 31 && (*ptrdate).month == 12 ) .....
scanf ( w%dx, &((*ptrdate).year) );


  (SP2) / .. 

158

161



  (SP2) / .. 

162

199 of 229

27

4? ) 6.8 ( 4)


main ( ) {
Date today;
PtrDate ptrdate;
ptrdate = &today;
ptrdate->day = 27;
ptrdate->month = 9;
ptrdate->year = 1985;
printf ( wToday\gs date is %2d/%2d/%4d\nx,
ptrdate->day, ptrdate->month, ptrdate->year );
}


  (SP2) / .. 

4@B @?1 ) I( @ @( ;A  


 .
:;.@8 QQ88- ). ) C
Date xmas = { 25, 12, 1986 };
Q=; @ @ @( ;A  
 .:;.@8 C
@34)
- ). )<  89@  ; @ Q1 external
;04 static  34) C
@3 A<BIJ@@( ;A:;. 0
Q ; @5 automatic B<  I A<A. 
34) C
@< B  :A

163



  (SP2) / .. 

164

6.10 ;DKhK9;W LWB:DW


@ :C.) - ). )4@B @:C.:=@6d34) QQ=.
?) I:C.) :=@6d34)4 ?><A.4@A.? C @ 
@W83.4 J=
34)/@)  B - ). ):C.@W8
3.4 J=34)/@) Q =  ; @:C.:=@6d34) Q
@
B I@W83.4 J=34)/@) <A./?) 1  7T)
/@) 1)8
64 BB ;= ?
8;04;= ?.4?  @ 
@W83.4 J=:=@6d1B:C.4 ?>3. C? C

@ 4. )-A?:C. ( )  ) *


staff
4. )IT)4 ?>34)- ). )
staff[i]
4. )IT) C
@ i :4 ?>
staff[i].forename 4. )IT)C04;. 34) C
@ I 34)4 ?>
staff[i].surname[j] 4. )IT) 4@6  j : @9=
34) C
@ i 34)4 ?>

Person staff[STAFFSIZE];


  (SP2) / .. 

165



  (SP2) / .. 

166

@ ?@:C.)  C
@8 ) :4 >?>34)
- ). )b H^)@>C

@ ?@:C.)  C
@9@ :4 >?>34)
- ). )b H^)@>C

@ :C.3.4 J= C
@Q = B4. )IT)-A?@ 4. )
b 88AC; 044 >?>< C H^)@>C
:C.:@ /
/>C04 C
@ 89 B?@:C.-A?
print_person ( staff[k] );

; @ .4)@ ?@:C.) H^)@>C  ( ) @81)4 >?>


C @ ?@:C.) H^)@>C ( @ ?)=( A8
4 >?> C04;. B .4))4 >?>Q=3 A34)
4 >?><?)H^)@>C 1 C
sort_forename ( staff, STAFFSIZE );
JQ88H^)@>C I@( ;AA.?
void sort_forename ( Person staff[ ], int size )

JQ88H^)@>C I@( ;AA.?


void print_person ( Person employee )


  (SP2) / .. 

28/04/2010

167



  (SP2) / .. 

168

200 of 229

28

6.11 ;DKhK GGE=DhJ


(Multi-dimensional Arrays)

@ @( ;A  
 .:;.@84 >?>34)
- ). )
@ @( ;A  
 .:;.@84 >?>34)- ). ) I( <A.
-A?
Person staff[ ] = { { wBloggsx, wJoex, MALE, 21 },
{ wSmithx, wJohnx, MALE, 30 },
{ wBlackx, wMaryx, FEMALE, 25 } };



  (SP2) / .. 

B @/012 b  04 )4 >?>B=@6d


34)4 >?>

A? Q 4 >?>4 BB  @@ 1

@W
<A. C 3.4 J= Q4834)@UT@6 Q = 
5 ?:C1 7T)Q8) Q@W8;= ? B/8
; @ .4)@ @W83.4 J= Q4834)@UT@6 Q =
 I:C.4 >?>

A? A) 4? )

169



  (SP2) / .. 

Q ; @/
 
 :;.@W83.4 J= Q48
34)
@UT@6 9@  B .4):C.4 >?>;= ?

3.
@?3.4) 4? )C@ @W83.4 J=
Q4834)@UT@6 2 -A?  Q
4834)@ 481)
1 5 1)

#define NUMBER_OF_PAPERS 5
int student [ NUMBER_OF_PAPERS ];
/* int student[5]; */
student[0] student[1] student[2] student[3] student[4]

5.6 8.5 12.6

24.1 16.0



  (SP2) / .. 

171



  (SP2) / .. 

 B 4)4 >?> 2

:=@6d@48A.?
QI(row) Q= 4= >(column) -A?3.4 J=4. )4
) 
Q@; ?IT) QI Q=3.4 J=IA 04 4= >

marks[2][8]
marks[0][0]
marks[0][1]
marks[row][column]
marks[0][8]
marks[1][8]
marks[1][0]
marks[0][2]
marks[2][0]
row

J 6.10 QA) 4? )@ @W83.4 J= Q34) @UT@6

28/04/2010

172

'78&' 2*1%% 2 -

$0!  1
2
3
4 5
  5.6 8.5 12.6 24.1 16.0
 &
6.0 7.2 15.0 25.0 18.0



  (SP2) / .. 

170

column

173



  (SP2) / .. 

174

201 of 229

29

-Q@ @ 8  4 >?> 2


B @=@6d  .4)@ @W83.4 J=A)@= B .4)


 ? 4 >?>/04@W83.4 J=:=@6d 2

 I
@ U4 >?>A) 1
#define NUMBER_OF_PAPERS
5
#define NUMBER_OF_STUDENTS 50
int
marks[NUMBER_OF_STUDENTS][NUMBER_OF_PAPERS];
/* int marks[50][5]; */


  (SP2) / .. 

*$6)&' 2*

#include<stdio.h>
main()
{ float score[10][3];
int i,j;
printf(wPlease put score\nx);
for(i=0;i<10;i++)
for(j=0;j<3;j++)
scanf(w%fx,&score[i][j]);
}

175

score[0][0] score[0][1] score[0][2]


score[1][0] score[1][1] score[1][2]

score[9][0] score[9][1] score[9][2]



  (SP2) / .. 

176

.,(( /3

score[0][0] score[0][1] score[0][2]


score[1][0] score[1][1] score[1][2]
score[2][0] score[2][1] score[2][2]

200 202 204 206 208 210


[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
210 212 214 216 218 220
[2][0] [2][1] [2][2] [3][0] [3][1] [3][2]
220 222 224 226 228 230
[4][0] [4][1] [4][2] [5][0] [5][1] [5][2]

score[9][0] score[9][1] score[9][2]




  (SP2) / .. 

28/04/2010

177

202 of 229

30

Stacks
Stack: what is it?
Applications
Implementation(s)

Computer Algorithm :
Analysis and Design
Krisana Chinnasarn, Ph.D.
Assistant Professor of Computer Science
Web: http://www.cs.buu.ac.th/~krisana
Stacks and Queues
Reading: Chap.3 Weiss

What is a stack?

Last In First Out

Stores a set of elements in a particular order


Stack principle: LAST IN FIRST OUT
= LIFO
It means: the last element inserted is the first one to be
removed
Example

Which is the first element to pick up?

B
top A

C
top B
A

D
top C
B
A

top

E
D
C
B
A

top

D
C
B
A

Array-based Stack
Implementation

Stack Applications

Allocate an array of some size (pre-defined)


Maximum N elements in stack

Real life

Bottom stack element stored at element 0


last index in the array is the top
Increment top when one element is pushed,
decrement after pop

Pile of books
Plate trays

More applications related to computer science


Program execution stack (read more from your text)
Evaluating expressions

28/04/2010

203 of 229

Stack Implementation:
CreateS, isEmpty, isFull

Push

Stack createS(max_stack_size) ::=


#define MAX_STACK_SIZE 100 /* maximum stack size */
typedef struct {
int key;
/* other fields */
} element;
element stack[MAX_STACK_SIZE];
int top = -1;

void push(int *top, element item)


{
/* add an item to the global stack */
if (*top >= MAX_STACK_SIZE-1) {
stack_full( );
return;
}
stack[++*top] = item;
}

Boolean isEmpty(Stack) ::= top< 0;


Boolean isFull(Stack) ::= top >= MAX_STACK_SIZE-1;

List-based Stack
Implementation: Push

Pop

void push(pnode top, element item)


{
/* add an element to the top of the stack */
pnode temp =
(pnode) malloc (sizeof (node));
if (IS_FULL(temp)) {
fprintf(stderr, The memory is full\n);
exit(1);
}
temp->item = item;
temp->next= top;
top= temp;
}

element pop(int *top)


{
/* return the top element from the stack */
if (*top == -1)
return stack_empty( ); /* returns and error key */
return stack[(*top)--];
}

10

Algorithm Analysis

Pop

push
pop
isEmpty
isFull

element pop(pnode top) {


/* delete an element from the stack */
pnode temp = top;
element item;
if (IS_EMPTY(temp)) {
fprintf(stderr, The stack is empty\n);
exit(1);
}
item = temp->item;
top = temp->next;
free(temp);
return item;
}

What if top is stored at the beginning of the


array?

11

28/04/2010

O(?)
O(?)
O(?)
O(?)

12

204 of 229

The Towers of Hanoi


A Stack-based Application

Towers of Hanoi

GIVEN: three poles


a set of discs on the first pole, discs of different sizes, the
smallest discs at the top
GOAL: move all the discs from the left pole to the right one.
CONDITIONS: only one disc may be moved at a time.
A disc can be placed either on an empty pole or on top of a
larger disc.

13

14

Towers of Hanoi

Towers of Hanoi

15

16

Towers of Hanoi

Towers of Hanoi

17

28/04/2010

18

205 of 229

Towers of Hanoi

Towers of Hanoi

19

20

Towers of Hanoi Recursive


Solution

Towers of Hanoi

void hanoi (int discs,


Stack fromPole,
Stack toPole,
Stack aux) {
Disc d;
if( discs >= 1) {
hanoi(discs-1, fromPole, aux, toPole);
d = fromPole.pop();
toPole.push(d);
hanoi(discs-1,aux, toPole, fromPole);
}

21

22

Is the End of the World


Approaching?

Queue

Problem complexity 2n
64 gold discs
Given 1 move a second

Stores a set of elements in a particular order


Stack principle: FIRST IN FIRST OUT
= FIFO
It means: the first element inserted is the first
one to be removed
Example

The first one in line is the first one to be


served

23

28/04/2010

24

206 of 229

Queue Applications

First In First Out

Real life examples


Waiting in line
Waiting on hold for tech support

Applications related to Computer Science


Threads
Job scheduling (e.g. Round-Robin algorithm for CPU
allocation)

rear
front

B
A

C
rear B
front A

D
rear C
B
front A

rear

25

Array-based Queue
Implementation
As with the array-based stack implementation,
the array is of fixed size

front rear Q[0] Q[1] Q[2] Q[3] Comments


-1
0
1
2
2
2

J1
J1
J1

J2
J2
J2

J3
J3
J3

front

26

Applications: Job Scheduling

-1
-1
-1
-1
0
1

rear

D
C
front B

queue is empty
Job 1 is added
Job 2 is added
Job 3 is added
Job 1 is deleted
Job 2 is deleted

A queue of maximum N elements

Slightly more complicated


Need to maintain track of both front and rear
Implementation 1

Implementation 2
27

28

Implementation 1:
createQ, isEmptyQ, isFullQ

Implementation 1:
enqueue

Queue createQ(max_queue_size) ::=


# define MAX_QUEUE_SIZE 100/* Maximum queue size */
typedef struct {
int key;
/* other fields */
} element;
element queue[MAX_QUEUE_SIZE];
int rear = -1;
int front = -1;
Boolean isEmpty(queue) ::= front == rear
Boolean isFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1

void enqueue(int *rear, element item)


{
/* add an item to the queue */
if (*rear == MAX_QUEUE_SIZE_1) {
queue_full( );
return;
}
queue [++*rear] = item;
}

29

28/04/2010

30

207 of 229

Implementation 1:
dequeue

Implementation 2:
Wrapped Configuration
EMPTY QUEUE
[3]

[2]

[2]

[3]
J2

element dequeue(int *front, int rear)


{
/* remove element at the front of the queue */
if ( *front == rear)
return queue_empty( ); /* return an error key */
return queue [++ *front];
}

[1]

[4]

[0]

[1]

[5]

front = 0
rear = 0

J3
[4]

J1

[0]

[5]

front = 0
rear = 3

Can be seen as a circular queue


31

32

Enqueue in a Circular Queue

Leave one empty space when queue is full


Why?
FULL QUEUE
[2]

[3]
J2

[1]

FULL QUEUE
[2]

[3]
J8

J3

J9

J4 [4][1] J7

J1
J5
[0]

[5]

front =0
rear = 5

void enqueue(int front, int *rear, element item)


{
/* add an item to the queue */
*rear = (*rear +1) % MAX_QUEUE_SIZE;
if (front == *rear) /* reset rear and print error */
return;
}
queue[*rear] = item;
}

[4]
J6
[0]

J5
[5]

front =4
rear =3

How to test when queue is empty?


How to test when queue is full?
33

34

List-based Queue
Implementation: Enqueue

Dequeue from Circular Queue

void enqueue(pnode &front, pnode rear, element item)

element dequeue(int* front, int rear)


{
element item;
/* remove front element from the queue and put it in item */
if (*front == rear)
return queue_empty( );
/* queue_empty returns an error key */
*front = (*front+1) % MAX_QUEUE_SIZE;
return queue[*front];
}

{ /* add an element to the rear of the queue */


pnode temp =
(pnode) malloc(sizeof (queue));
if (IS_FULL(temp)) {
fprintf(stderr, The memory is full\n);
exit(1);
}
temp->item = item;
temp->next= NULL;
if (front) { (rear) -> next= temp;}
else front = temp;
rear = temp; }
35

28/04/2010

36

208 of 229

Algorithm Analysis

Dequeue

enqueue
dequeue
size
isEmpty
isFull

element dequeue(pnode &front) {


/* delete an element from the queue */
pnode temp = front;
element item;
if (IS_EMPTY(front)) {
fprintf(stderr, The queue is empty\n);
exit(1);
}
item = temp->item;
front = temp->next;
free(temp);
return item;
}

What if I want the first element to be always at


Q[0] ?

37

28/04/2010

O(?)
O(?)
O(?)
O(?)
O(?)

38

209 of 229

The British Constitution


Crown

Computer Algorithm :
Analysis and Design

Church of

House of

House of

Supreme

Commons

Lords

Court

Cabinet

England

Ministers

Krisana Chinnasarn, Ph.D.


County

Assistant Professor of Computer Science


Web: http://www.cs.buu.ac.th/~krisana
Trees. Binary Trees.
Reading: Chap.4 (4.1-4.2) Weiss

Metropolitan
Council
police

More Trees Examples

Rural District

County Borough

Council

Council

Definition of Tree

Unix / Windows file structure


A tree is a finite set of one or more nodes
such that:
There is a specially designated node called
the root.
The remaining nodes are partitioned into n>=0
disjoint sets T1, ..., Tn, where each of these sets is
a tree.
We call T1, ..., Tn the subtrees of the root.

Terminology

Level and Depth

node (13)
degree of a node
leaf (terminal)
nonterminal
parent
children
sibling
degree of a tree (3)
ancestor
level of a node
height of a tree (4)

The degree of a node is the number of subtrees


of the node

Level
3
2
E

2
0

40

30
L

2 1
F

30

A
C
G

2
31
0

3
H

The degree of A is 3; the degree of C is 1.

30

D
I

30

The node with degree 0 is a leaf or terminal


node.
A node that has subtrees is the parent of the
roots of the subtrees.
The roots of these subtrees are the children of
the node.
Children of the same parent are siblings.
The ancestors of a node are all the nodes
along the path from the root to the node.

33
4

28/04/2010

210 of 229

Tree Properties
Property
Number of nodes
Height
Root Node
Leaves
Interior nodes
Number of levels
Ancestors of H
Descendants of B
Siblings of E
Right subtree

A
C

G
H

Representation of Trees

Value

List Representation
( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
The root comes first, followed by a list of sub-trees

data

link 1 link 2 ...

link n

How many link fields are


needed in such a representation?

A Tree Node

Left Child - Right Sibling

Every tree node:


object useful information
children pointers to its children nodes

data
left child right sibling

B
O
F

E
O

O
K

O
9

10

Tree ADT

Tree Implementation
typedef struct tnode {
int key;
struct tnode* lchild;
struct tnode* sibling;
} *ptnode;

Objects: any type of objects can be stored in a tree


Methods:
accessor methods
root() return the root of the tree
parent(p) return the parent of a node
children(p) returns the children of a node

- Create a tree with three nodes (one root & two children)
- Insert a new node (in tree with root R, as a new child at level L)
- Delete a node (in tree with root R, the first child at level L)

query methods
size() returns the number of nodes in the tree
isEmpty() - returns true if the tree is empty
elements() returns all elements
isRoot(p), isInternal(p), isExternal(p)

11

28/04/2010

12

211 of 229

Tree Traversal

Preorder

Two main methods:


preorder traversal

Preorder
Postorder

Algorithm preOrder(v)
visit node v
for each child w of v do
recursively perform preOrder(w)

Recursive definition
PREorder:
visit the root
traverse in preorder the children (subtrees)

POSTorder
traverse in postorder the children (subtrees)
visit the root
13

14

Postorder

Preorder Implementation
public void preorder(ptnode t) {
ptnode ptr;
display(t->key);
for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) {
preorder(ptr);
}
}

postorder traversal
Algorithm postOrder(v)
for each child w of v do
recursively perform postOrder(w)
visit node v

du (disk usage) command in Unix

15

16

Postorder Implementation

Binary Trees

public void postorder(ptnode t) {


ptnode ptr;
for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) {
postorder(ptr);
}
display(t->key);
}

A special class of trees: max degree for each node


is 2
Recursive definition: A binary tree is a finite set
of nodes that is either empty or consists of a root
and two disjoint binary trees called the left
subtree and the right subtree.
Any tree can be transformed into binary tree.
by left child-right sibling representation

17

28/04/2010

18

212 of 229

Example

ADT Binary Tree


A
B

objects: a finite set of nodes either empty or


consisting of a root node, left BinaryTree,
and right BinaryTree.
method:
for all bt, bt1, bt2 BinTree, item element
Bintree create()::= creates an empty binary tree

E
F

G
H

Boolean isEmpty(bt)::= if (bt==empty binary


M

tree) return TRUE else return FALSE


J

19

20

Samples of Trees
BinTree makeBT(bt1, item, bt2)::= return a binary tree
whose left subtree is bt1, whose right subtree is bt2,
and whose root node contains the data item
Bintree leftChild(bt)::= if (IsEmpty(bt)) return error
else return the left subtree of bt
element data(bt)::= if (IsEmpty(bt)) return error
else return the data in the root node of bt
Bintree rightChild(bt)::= if (IsEmpty(bt)) return error
else return the right subtree of bt

1
B

B
Skewed Binary Tree

C
D
E

Maximum Number of Nodes in BT

5
4

21

22

Relations between Number of


Leaf Nodes and Nodes of Degree 2

For any nonempty binary tree, T, if n0 is the


number of leaf nodes and n2 the number of nodes
of degree 2, then n0=n2+1
proof:
Let n and B denote the total number of nodes &
branches in T.
Let n0, n1, n2 represent the nodes with no children,
single child, and two children respectively.
n= n0+n1+n2, B+1=n, B=n1+2n2 ==> n1+2n2+1= n,
24
n1+2n2+1= n0+n1+n2 ==> n0=n2+1

The maximum number of nodes on level i of a


binary tree is 2i-1, i>=1.
The maximum nubmer of nodes in a binary tree
of depth k is 2k-1, k>=1.

Prove by induction.
k

2i 1 = 2 k 1
i =1

23

28/04/2010

Complete Binary Tree

213 of 229

Binary Tree Representations

Full BT vs. Complete BT


A full binary tree of depth k is a binary tree of
depth k having 2k-1 nodes, k>=0.
A binary tree with n nodes and depth k is
complete iff its nodes correspond to the nodes numbered
from 1 to n in the full binary tree of depth k.
A

C
E

Complete binary tree

C
D
E

A [1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
.
[16]

Full binary tree of depth


4
25

Sequential
Representation

parent(i) is at i/2 if i!=1. If i=1, i is at the root and


has no parent.
leftChild(i) is at 2i if 2i<=n. If 2i>n, then i has no
left child.
rightChild(i) is at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.

B
D

If a complete binary tree with n nodes (depth =


log n + 1) is represented sequentially, then for
any node with index i, 1<=i<=n, we have:

[1]
[2]
[3]
[4]
(1) waste space
(2) insertion/deletion [5]
[6]
problem
[7]
[8]
A
[9]

A
B
-C
---D
-.
E

26

A
B
C
D
E
F
G
H
I

Linked Representation
typedef struct tnode *ptnode;
typedef struct tnode {
int data;
ptnode left, right;
};

data
left

data

right

left

27

28

Binary Tree Traversals

Arithmetic Expression Using BT


+

Let L, V, and R stand for moving left, visiting


the node, and moving right.
There are six possible combinations of traversal

lRr, lrR, Rlr, Rrl, rRl, rlR


*

Adopt convention that we traverse left before


right, only 3 traversals remain
A
29

D
C

lRr, lrR, Rlr


inorder, postorder, preorder

28/04/2010

right

inorder traversal
A/B*C*D+E
infix expression
preorder traversal
+**/ABCDE
prefix expression
postorder traversal
AB/C*D*E+
postfix expression
level order traversal
+*E*D/CAB
30

214 of 229

Inorder Traversal (recursive version)

Preorder Traversal (recursive version)


void preorder(ptnode ptr)
/* preorder tree traversal */
{
+**/ABCDE
if (ptr) {
printf(%d, ptr->data);
preorder(ptr->left);
predorder(ptr->right);
}
}

void inorder(ptnode ptr)


/* inorder tree traversal */
{
A/B*C*D+E
if (ptr) {
inorder(ptr->left);
printf(%d, ptr->data);
indorder(ptr->right);
}
}
31

32

Level Order Traversal

Postorder Traversal (recursive version)

(using queue)

void levelOrder(ptnode ptr)


/* level order tree traversal */
{
int front = rear = 0;
ptnode queue[MAX_QUEUE_SIZE];
if (!ptr) return; /* empty queue */
enqueue(front, &rear, ptr);
for (;;) {
ptr = dequeue(&front, rear);

void postorder(ptnode ptr)


/* postorder tree traversal */
{
AB/C*D*E+
if (ptr) {
postorder(ptr->left);
postdorder(ptr->right);
printf(%d, ptr->data);
}
}
33

34

Euler Tour Traversal


generic traversal of a binary tree
the preorder, inorder, and postorder traversals are
special cases of the Euler tour traversal
walk around the
tree and visit each
node three times:

if (ptr) {
printf(%d, ptr->data);
if (ptr->left)
enqueue(front, &rear,
ptr->left);
if (ptr->right)
enqueue(front, &rear,
ptr->right);
}
else break;
+*E*D/CAB
}

on the left
from below
on the right

}
35

28/04/2010

36

215 of 229

Euler Tour Traversal (contd)

Euler Tour Traversal (contd)


preorder traversal = Euler Tour with a visit only on
the left
inorder = ?
postorder = ?
Other applications: compute number of descendants
for each node v:

eulerTour(node v) {
perform action for visiting node on the left;
if v is internal then
eulerTour(v->left);
perform action for visiting node from below;
if v is internal then
eulerTour(v->right);
perform action for visiting node on the right;
}

counter = 0
increment counter each time node is visited on the left
#descendants = counter when node is visited on the right
counter when node is visited on the left +
1

Running time for Euler Tour?


37

38

Application: Evaluation of
Expressions
+
*
*

D
C

/
B

Inorder Traversal (recursive version)

inorder traversal
A/B*C*D+E
infix expression
preorder traversal
+**/ABCDE
prefix expression
postorder traversal
AB/C*D*E+
postfix expression
level order traversal
+*E*D/CAB

void inorder(ptnode ptr)


/* inorder tree traversal */
{
A/B*C*D+E
if (ptr) {
inorder(ptr->left);
printf(%d, ptr->data);
inorder(ptr->right);
}
}

39

40

Preorder Traversal (recursive version)

Postorder Traversal (recursive version)

void preorder(ptnode ptr)


/* preorder tree traversal */
{
+**/ABCDE
if (ptr) {
printf(%d, ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}

void postorder(ptnode ptr)


/* postorder tree traversal */
{
AB/C*D*E+
if (ptr) {
postorder(ptr->left);
postorder(ptr->right);
printf(%d, ptr->data);
}
}

41

28/04/2010

42

216 of 229

Application:
Propositional Calculus Expression

Propositional Calculus Expression


(x1 x2) ( x1 x3) x3

A variable is an expression.
If x and y are expressions, then x, xy,
xy are expressions.
Parentheses can be used to alter the normal
order of evaluation ( > > ).
Example: x1 (x2 x3)

X1

Node Structure
value

X3

X1

postorder traversal (postfix evaluation)


44

43

data

X3

X2

left

Postorder Eval
right

void post_order_eval(ptnode node)


{
/* modified post order traversal to evaluate a propositional
calculus tree */
if (node) {
post_order_eval(node->left);
post_order_eval(node->right);
switch(node->data) {
case not: node->value =
!node->right->value;
break;

typedef emun {not, and, or, true, false } logical;


typedef struct tnode *ptnode;
typedef struct node {
logical
data;
short int
value;
ptnode right, left;
};

45

46

Postorder Eval (contd)


case and: node->value =
node->right->value &&
node->left->value;
break;
case or:
node->value =
node->right->value | |
node->left->value;
break;
case true: node->value = TRUE;
break;
case false: node->value = FALSE;
}
}
}
47

28/04/2010

217 of 229

Contents
1. Definitions and Representations

Computer Algorithm :
Analysis and Design

2. A Minimum Spanning Tree Algorithm


3. A Shortest-Path Algorithm
4. Traversing Graphs and Digraphs

Krisana Chinnasarn, Ph.D.


Assistant Professor of Computer Science
Web: www.cs.buu.ac.th/~krisana
Graphs (I)
Reading: Chap.9 : Weiss, Chap.4 :Baase

Applications

What is a Graph?

networks (roads, flights,


communications)

V= {a,b,c,d,e}

JFK

E= {(a,b),(a,c),(a,d),
(b,e),(c,d),(c,e),
(d,e)}

CS16

electronic circuits

A graph G = (V,E) is composed of:


V: set of vertices
E: set of edges connecting the vertices in V
An edge e = (u,v) is a pair of vertices
Example:

LAX

STL

HNL

DFW
FTL

Terminology:
Adjacent and Incident

Terminology:
Degree of a Vertex

If (v0, v1) is an edge in an undirected graph,

The degree of a vertex is the number of edges


incident to that vertex
For directed graph,

v0 and v1 are adjacent


The edge (v0, v1) is incident on vertices v0 and v1

If <v0, v1> is an edge in a directed graph

the in-degree of a vertex v is the number of edges


that have v as the head
the out-degree of a vertex v is the number of edges
that have v as the tail
if di is the degree of a vertex i in a graph G with n
vertices and e edges, the number of edges is

v0 is adjacent to v1, and v1 is adjacent from v0


The edge <v0, v1> is incident on v0 and v1

n 1

e=(

d
0

28/04/2010

)/2

Why? Since adjacent vertices each


count the adjoining edge, it will be
counted twice
6

218 of 229

Terminology:
Path

Examples
0
3

3
3 1

2 3

6
1

1 G2 1
in:1, out: 1

in: 1, out: 2

in: 1, out: 0

3G1

directed graph
in-degree
out-degree

path: sequence of
vertices v1,v2,. . .vk such
that consecutive
vertices vi and vi+1 are
adjacent.

3
3

b
c

c
e d

d
abedc

G3

e
bedc

Even More Terminology

More Terminology
simple path: no repeated vertices
a

connected graph: any two vertices are connected by some path

b
bec

c
e

cycle: simple path, except that the last vertex is the same as
the first vertex
a

connected

not connected

subgraph: subset of vertices and edges forming a graph


connected component: maximal connected subgraph. E.g., the graph
below has 3 connected components.

b
acda

c
e

10

Subgraphs Examples
0
1

2
3
G1
0

1
(i)

0
1

(i)

(iii)
(b) Some of the subgraph of G3

tree

3(iv)

(ii)

tree - connected graph without cycles


forest - collection of trees

28/04/2010

(ii)
(iii)
(a) Some of the subgraph of G1

G3

More

tree

for est
tree
tree

(iv)
11

12

219 of 229

Connectivity

More Connectivity

Let n = #vertices, and m = #edges


A complete graph: one in which all pairs of vertices
are adjacent
How many total edges in a complete graph?

n = #vertices
m = #edges
For a tree m = n - 1

Each of the n vertices is incident to n-1 edges, however, we


would have counted each edge twice! Therefore, intuitively, m
= n(n -1)/2.

n=5
m=4

If m < n - 1, G is
not connected

Therefore, if a graph is not complete, m < n(n -1)/2

n=5
m=3

n=5
m = (5 4)/2 = 10
13

14

Oriented (Directed) Graph

Directed vs. Undirected Graph

A graph where edges are directed

An undirected graph is one in which the pair


of vertices in a edge is unordered, (v0, v1) =
(v1,v0)
A directed graph is one in which each edge is
a directed pair of vertices, <v0, v1> != <v1,v0>
tail

head

15

16

ADT for Graph

Graph Representations

objects: a nonempty set of vertices and a set of undirected edges, where each
edge is a pair of vertices
functions: for all graph Graph, v, v1 and v2 Vertices
Graph Create()::=return an empty graph
Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no
incident edge.
Graph InsertEdge(graph, v1,v2)::= return a graph with new edge
between v1 and v2
Graph DeleteVertex(graph, v)::= return a graph in which v and all edges
incident to it are removed
Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1, v2)
is removed
Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE
else return FALSE
List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v

Adjacency Matrix
Adjacency Lists

17

28/04/2010

18

220 of 229

Examples for Adjacency Matrix

Adjacency Matrix

Let G=(V,E) be a graph with n vertices.


The adjacency matrix of G is a two-dimensional
n by n array, say adj_mat
If the edge (vi, vj) is in E(G), adj_mat[i][j]=1
If there is no such edge in E(G), adj_mat[i][j]=0
The adjacency matrix for an undirected graph is
symmetric; the adjacency matrix for a digraph
need not be symmetric

3
1
0
1
1

1
1
0
1

0 1 0

1 0 1
0 0 0

G2

G1

symmetric
undirected: n2/2
directed: n2

7
0
1

0
0

0
0

1 1
0 0
0 0
1 1
0 0
0 0
0 0
0 0

0 0 0 0 0
1 0 0 0 0
1 0 0 0 0

0 0 0 0 0
0 0 1 0 0

0 1 0 1 0
0 0 1 0 1

0 0 0 1 0

G4

19

Merits of Adjacency Matrix

1
1
1

0
1

20

Adjacency Lists (data structures)


Each row in adjacency matrix is represented as an adjacency list.

From the adjacency matrix, to determine the


connection of vertices is easy
n 1
The degree of a vertex is adj _ mat[i][ j]
j =0
For a digraph (= directed graph), the row sum is
the out_degree, while the column sum is the
in_degree
n 1

n 1

j =0

j =0

#define MAX_VERTICES 50
typedef struct node *node_pointer;
typedef struct node {
int vertex;
struct node *link;
};
node_pointer graph[MAX_VERTICES];
int n=0; /* vertices currently in use */

ind (vi ) = A[ j , i ] outd (vi ) = A[i , j ]

21

0
1

1
0
0
0

1
0

3
3
3
2
0

2
G3

Some Operations

6
7

2
2
1
1
G1

0
1
2

3
0
1
2
3

22

1
2

0
1
2
3
4
5
6
7

1
0
0
1
5
4
5
6
G4

degree

2
3
3
2

# of nodes in adjacency list


#

of edges in a graph
determined in O(n+e)

out-degree

6
7

of a vertex in a directed graph

# of nodes in its adjacency list


in-degree

of a vertex in a directed graph

traverse the whole data structure

23 nodes
An undirected graph with n vertices and e edges ==> n head nodes and 2e list

28/04/2010

of a vertex in an undirected graph

24

221 of 229

1. Definitions and
Representations

2. Min-Cost Spanning Tree

Representations

2
1

Adjacency Matrix
Adjacency Lists
Adjacency Multi-lists

3
1

G=(V, E, W)

2 1

weight

Vertex

LLLL

Greedy

(1) Sort E in the non-decreasing order of weights

2
3

NIL

NIL

O(eloge)
n2logn Why?
(2) Choose n1 edges from the sorted list of E
as long as the current selected edge does not
form a cycle with the previously-chosen edges

NIL

O(eloge + eG(n))
Kruskals algorithm !!!
Any Better way ?

3
NIL
25

26

Observation
A

1
3

15

1 3

20
2

5
C

G = (V, E, W)

tree vertices = {A, B, C} = VT


fringe vertices = {E,F,D} = VF

Why not local search ?

unseen vertices = {G, H} = VU


CE = {{A,D},{B,E},{C,F}}

27

28

Dijkstra / Prim Algorithm

Dijkstra / Prim Algorithm

B
1

C
2

29

28/04/2010

Select an arbitrary vertex to start the tree;


WHILE there are fringe vertices do
select an edge of minimum weight between a tree vertex
and a fringe vertex;
add the selected edge and the fringe vertex to the tree;
end

5
2

30

222 of 229

B
1

C
2

B
1

4
3

VT = { A }

VT = { A, C }

VF = { C, B, D }

VF = { B, D, E }

CE = { { A, C }, { A, B }, { A, D } }
3
1
4

CE = { { A, D }, { C, B }, { C, E } }
7
3
2
31

VT = { A, B, C }

B
1

C
2

B
1

4
3

32

5
2

VT = { A, B, C, D }

VF = { D, E }

VF = { E }

CE = { { B, D }, { B, E } }
1

CE = { { D, E } }

5
33

B
1

SI { Select an arbitrary vertex to start the tree }


vT = , vF = , CE = ;
vT = vT U {v} ;
Update vF and CE ;

C
2

4
3

34

while vF do ;
e : = min - weight edge in CE ;
Update vT, vF, CE ;
end {while}

5
2

VT = { A, B, C, D, E }
VF =

No sorting !!!
Why this algorithm works ?

CE =
35

28/04/2010

36

223 of 229

Lemma : Let G = ( V, E, W ) be a connected weighted graph


and E' E be a subset of the edges in some minimum
spanning tree T = ( V, ET ) for G. Let V' be the vertices
incident with edges in E'. If { x, y } is an edge of
minimum weight such that x V' and y V', then
E' U {x, y} ET.

x
y

[Proof]

T' = (V', E' )


y

T' T
T= (V, ET)

w
v

y
i) {x, y} ET trivial
ii) {x, y} ET
See the figure.
37

38

Algorithm : Minimum spanning tree(Dijkstra/Prim)

Time complexity

Input : G = (V,E,W), a weighted graph.


Output : The edges in a minimum spanning tree.
1. { Initialization }
Let x be an arbitrary vertex ;
ET:= ; stuck := false ; VT:={x};

Kruskal
Dijkstra & Prim

2. { Main loop ; x has just been brought into the tree. Update fringe and candidates. }
while VT V and not stuck do
3.
{ Replace some candidate edges. }
for each fringe vertex y adjacent to x do
Update
if W(xy) < W(the candidate edge e incident with y) then
candidate
xy replaces e as the candidate edge for y ;
edges
end { if }
end{for}
4.
{ Find new fringe vertices and candidate edges. }
for each unseen y adjacent to x do
Add new fringe vertices
y is now a fringe vertex and xy is a candidate ;
and edges. (candidate)
end { for } ;
5.
{ Ready to choose next edge. }
if there are no candidates then stuck := true { no spanning tree} ;
else
6.
{ Choose next edge. }
Find a candidate edge e, with minimum weight ;
x := the fringe vertex incident with e.
Add x and e to the tree.
{ x and e are no longer fringe and candidate. }
Choose new edges.
end { if }
end { while }
39

40

Algorithm : Minimum spanning tree (Dijkstra/Prim)


1. { Initialization }
Let x be an arbitrary vertex ;
ET:= ; stuck := false ; VT:={x} ;
O(n)
2. { Main loop ; x has just been brought into the tree.
Update fringe and candidates. }
while VT V and not stuck do
3. { Replace some candidate edges. }
for each fringe vertex y adjacent to x do
if W(xy) < W(the candidate edge e incident with y) then
xy replaces e as the candidate edge for y ;
end { if }
end{for}
O(|E|)
4. { Find new fringe vertices and candidate edges. }
for each unseen y adjacent to x do
y is now a fringe vertex ;
xy is now a candidate ;
end { for } ;
5. { Ready to choose next edge. }
if there are no candidates then stuck := true { no spanning tree} ;
else
6. { Choose next edge. }
Find a candidate edge e, with minimum weight ;
x := the fringe vertex incident with e.
Add x and e to the tree.
O(n2)
{ x and e are no longer fringe and candidate. }
end { if }
end { while }

( By induction on # of edges chosen )


min-cost edge

(m=1)

(m=k)

Assume that all the edges so far selected


are in a min-cost spanning tree for G.

( m = k+1) By the previous Lemma, the result follows.

28/04/2010

O (e + n 2 )
O(e + n log n)

Theorem : Dijkstra/Prim Algorithm correctly


constructs a min-cost spanning tree.
[proof]

O (e log e + eG (e))

41

O(|E|+n2)
42

224 of 229

fringeLink
B

3
6
7
G
3 2 C
F 5 1
I 4 H
2
6
8
2
E 1 D
4

2
A
3

parent

A
B
C
D
E
F
G
H
I

Lower Bound

adjacencyList

fringeWgt

status

(|E|)
Why ?
(1) a trivial lower bound O(|V| + |E|) = O(|E|)
(2) adversary argument
Every edge is required to be examined at least once.
Why ?
Suppose that some edge e is not examined at all.
(see below)

intree

nil
F

2
4

A
B

intree
fringe
unseen

(Adjacency lists
are not shown.
Nodes are
assumed to be in
alphabetical order
within each list.)

unseen

nil
F
C
H

7
3
3
1

A
A
G
G

fringe
intree

2
12 e

fringe
4

fringe

Shaded entries in fringeLink are


no longer in use. fringeList = I.

14

G = (V, E)

10 15

w(f) 2

fE/{e}

11
12
7
9
5

e must not be contained in a min-cost spanning tree.


why ?
Now, w(e) = 1
Contradiction ! why ?
(|E|)

[ Minimum spanning tree data structure ]

43

44

45

46

3. A shortest path algorithm


P : Given G = (V, E, W) and s,d V,
find a shortest path between s and d.
Does the Dijkstra/Prim algorithm also work for
solving the shortest path finding problem?
No !!!

Why ?

Dijkstras Algorithm
1

Step 0
{ initialization }
v1 := 0
vj := w1j, j = 2, 3, 4,, n
p := {1}, T := {2, 3, 4,, n}
Step 1
{ Designation of permanent of label }
find k such that vk =min
{ vj }
j T
T := T \{k}
P := P U {k}
if T = , stop ( if k = d, stop )
Step 2
{ Revision of Tentative label }
vj := min{ vj, vk + wkj ) j T
go to step 1.

2
4

s1 d4
w12 = 1, w23 = 3, w24 = 2, w34 =2

v1 := 0, v2 = 1, v3 = , v4 =
P := {1}, T := {2, 3, 4}
min{vj} = min{v2, v3, v4}
1

jT

k=2
Is k=4 ? No !!!
T := {2,3,4}/{2} = {3,4}
P := P U{2} = {1,2}
v3 = min{v3, v2+w23} = min{, 1+3} = 4
v4 = min{v4, v2+w24} = min{, 1+2} = 3
min{vj} = min{v3, v4} = min{4, 3} = v4

T := {3,4}/{4} = {3}
P := P U{4} = {1,2,4}
Is k=4 ? Yes !!!

jT

k=4

47

28/04/2010

48

225 of 229

4. Traversing Graphs and


Digraphs

Why does Dijkstras Algorithm


Work ?

start
8 Queen Problem
Recursion
Q

y'
x'


Q
Q
Q

(1,1)

(2,3)

(3,5)

(1,2) (1,3)
(1,4) (1,5) (1,6) (1,7) (1,8)
(2,4)

(2,5) (2,6) (2,7) (2,8)

(3,6)

(3,7)

(3,8)

Depth First Search

y
(4,2)

(4,7)

(4,8)

e
(5,4)

(5,8) (5,2) (5,4) (5,3) (5,4)

min
(6,4)

(6,4)

(7,6)

(7,6)

49

50

C
H

E
A

A
B

B
C
1

C
1
2

C
1
1
2

1
C
1
2

1
2

1
Depth First Search

Breadth First Search


51

F
I
6

B
2

3 C

E
Depth First Search

A 7
1

52

A
F

I
6

F 6

C
3
H 5
4

1
4

3
7 C

E
Breadth First Search

DFS tree

1 A
3 B4
C
7
H

2
5
E

6
I

BFS tree

E
procedure BFS(AdjList : HeaderList; v : VertexType)
var
Q: Queue
w: VertexType
begin
Q:=
visit and mark v; insert v in Q;
while Q do
x := Front(Q);
for each unmarked vertex w adjacent to x do
visit and mark w;
insert w in Q;
end{for};
end{while}
end{BFS}

procedure DFS (AdjList : HeaderList; v : VertexType)


var
s: Stack
w: VertexType
begin
s:=
visit, mark, and stack v;
while s!= do
while there are unmarked vertex w adjacent to Top(s) do
visit, mark, and stack w
end{while};
pop s;
end{outer while}
end{DFS}
53

28/04/2010

54

226 of 229

Depth First Search Tree ( Directed Graph )

Depth First Search

B
2

undirected graphs
G

C
H

A 7
1

C
3
H 5
4

I
6
E

Tree edges
Back edges
Cross edges
Descendant edges
(forward)

Tree edges
Back edges
(no other types)

Note : (1) top


(2) left

why not in
undirected graph?

down
right

55

56

Applications: Finding a Path

DFS vs. BFS


DFS Process

Find path from source vertex s to destination


vertex d
Use graph search starting at s and terminating
as soon as we reach d

start

destination

Need to remember edges traversed


A DFS on A

Use depth first search ?


Use breath first search?

G
D
B
A
57

B DFS on B
A

Call DFS on G

C
B
A

DFS on C

Call DFS on D

B
A

Return to call on B

found destination - done!


Path is implicitly stored in DFS recursion
Path is: A, B, D, G
58

DFS vs. BFS


F

G
destination

start

BFS Process

rear

front

A
Initial call to BFS on A
Add A to queue
rear

rear

front

rear

front

D C

Dequeue A
Add B

Dequeue B
Add C, D

rear

front

D
Dequeue C
Nothing to add

front

G
Dequeue D
Add G

found destination - done!


Path must be stored separately

59

28/04/2010

227 of 229

10


 
,  
 Computer Algorithm: Analysis and Design,
 

     , 2553
  ! "#$, #$%&'()*
+,& -. C,
%  & $ ' , 2553.
  ! "#$,  #/0,1,  ,
%  & &
), 2552

28/04/2010

228 of 229

 
  
 !" 11/2553
(")  (") *)+,- . ) 

 )
)
********************

    
            !   

"#$"   %   !%" !&'  ()*+,-!.

   
  
    /   ,% /+$"%1.
2.
3.
4.
5.
6.
7.
8.
9.

  (  ./ /

  (  . 7
  (  .(,
  (  $ 
  (  &% ,?
: /+  (  .
A8!
: /+  (  ./ 
..
 (  ( !

  ,
 %
:+;< %
,& ,
88
" !
:
/
 %C  ,?
( <
(. 

((.3 4)
(
8   )
( "
)
(
!,)
(
!,)
(  )
(
8   )
(  )
(  )

" !& !.




.


.


.


.


.


.


.


.


,-%-,- + , %-"# $"


" !
  ,% 5 %  2553

(  (  .. ../8. , ,)


 
    +" !$ !  /"C,'

28/04/2010

229 of 229

You might also like