Introduction to Procedural Programming - Part III

In this post I will discuss "How To" Procedular Programming.
Lets begin.
We know that programming is logical arrangement of statements (code) targed to obtain certain goal. Every code (statement) except to non-executable are meant to perform certain action. In procedural programming we will segment (divide) these blocks into several manageable parts (procedures/sub-program). For example, a problem of testing where a number is prime, we will write around 7-8 lines code of program; we can think this problem in procedural way- first there is need of a procedure which accepts a input number and second the number is passed  in another procedure which operates number in testing whether number is prime and returns result then finally there is a need of third procedure which will provide the result (output) to the user.
Here students may find little difficult or misleading or may think in different way. I want to aware you that how would you segment programs into several procedure depends I don't say you will be wrong; ya in the beginning it may be little confusion, but not get overloaded. Slowly with revisions and illustration programs you will finally grab the concepts and then onward it will be habitual.
Lets take a look on above illustration in the form of program (if you don't understand program don't get upset; only try to catch concept of procedures):

Program: testing whether number is prime (structure program- no procedures)
CLS
REM asking user to input a number to test for prime
INPUT "Enter a testing number"; n
REM test whether number is prime; set flag f to 1 (we first assume that n is prime)
f=1
FOR i=2 TO n/2
  IF n mod i=0 THEN f=0 : EXIT FOR
NEXT i
REM check value of f to decide prime/composite and display result to the user
IF f=1 THEN
  PRINT n;" is Prime Number!"
ELSE
  PRINT n; " is Composite Number!"
ENDIF
END

Program: testing whether number is prime (Procedural - 1 sub-routines and 2 function)
[Here. ACCEPT function askes testing number and returns to module (calling program)
 ISPRIME function with a value passed through parameter returns 1 if the value is prime
 DISPLAY sub-routine will display the result on the screen]
DECLARE FUNCTION accept()
DECLARE FUNCTION isPrime(num)
DECLARE SUB display(testnum, result)
CLS
v=accept
REM isPrime function is invoked then its return is passed to the display (see more-Functional Operator)
CALL display(v, isPrime(v))
END

FUNCTION accept
INPUT "Enter a testing number="; n
accept=n
END FUNCTION

FUNCTION isPrime(num)
f=1
FOR i=2 TO num/2
  IF num MOD i=0 THEN f=0 : EXIT FOR
NEXT i
isPrime=f
END FUNCTION

SUB display(testnum, result)
IF result=1 THEN
  PRINT testnum;" is Prime!"
ELSE
 PRINT testnum;" is Composite!"
ENDIF
END SUB

For more see upcoming post.
Best wishes!!!

No comments:

Post a Comment