Elementary Programming Concepts



Programming language : A combination of restricted vocabulary (words and symbols) and a syntax (rules ) is called a programming language.

A programming language is a medium used by the users to communicate and write instruction for a computer.


Generation of computer programming languages :
The programming languages are classified into five generations:
i)                    First generation ( machine language )
ii)                  Second generation ( assembly language )
iii)                Third generation [3GL] (high level language)
iv)                Fourth generation (4GL)
v)                  Fifth generation


Types of programming languages:
There are various types of programming languages that can be categorized into four types:
i)                    High level programming language (e.g. Qbasic, COBOL etc.)
ii)                  Middle level programming language ( e.g. C )
iii)                Low level programming language (e.g. Assembly language)
iv)                Machine language (e.g. instructions written using 0’s and 1’s )


Programming – the process of writing instructions for computer by using computer programming language is called as programming or coding.


Program – A set or collection of sequential instruction grouped together to perform a specific task is called a program.



Software – a set or collection of various and similar programs makes a software.
                                   
          PROGRAMING LANGUAGE

                                                INSTRUCTION
           
                                                   PROGRAM

                                                   SOFTWARE


Programmer – Computer programmers are responsible for designing, writing and modifying computer programs. Programmers can be classified into two categories:

a)      System programmer
b)      Application programmer


Program development cycle:
The basic steps involved in developing a program are –
1.      Define the problem
2.      Analyze the problem
3.      Designing a solution (algorithm, flowchart)
4.      Coding the solution
5.      Testing and debugging the program
6.      Document the program
7.      Implementation and maintenance


Tools for designing a program:
a) 
    Algorithm – A set sequential steps that specify the solution to a given problem is called an algorithm.

Algorithm to find a greater value among the two values :
STEP 1:  START
STEP 2:  Read two values using variable x and y
STEP 3:  Is x greater than y
                If yes print x is greater
                If no print y is greater
STEP 4:  STOP


Flowchart – Symbolic visual representation of an algorithm is called a flowchart.

Advantages of flowchart:
a)      Representing algorithm by flowchart and than converting it to computer program is easier and accurate than writing the program directly.
b)      Flowcharts are independent of any programming languages. Hence the algorithm given in a flowchart can be translated into more than one programming languages.


General symbols used in flowchart

Oval : Start or End
 


Parallelogram : Input and output [ data and instructions to be given to the computer and then result of processing.
 


Rectangle : To perform processing.
 



Diamond: Decision making [ The comparison and conditions are checked . This allows the program for branching and looping. The statements are also tested here.
 





Flowlines:
 


Connector:
 










Characters used in Qbasic :
a)      Alphabetic characters ( A to Z )
b)      Numeric characters ( 0 to 9 )
c)      Special characters (“” , ; ,! etc.)
d)      Function keys ( F1 to F12 )

Elementary data types used in Qbasic :
Qbasic supports two data types represented by variable which are :
a) Numeric
b) String

Variable – a symbol whose value changes during the program execution is called a variable.
For example in x = y + z ( the value of x varies depending upon the values of y and z.)

Numeric variable – A symbol that is used to store a number is known as numeric variable.
For example a= 9 and b =1.5

Types of numeric variable :
A numeric variable can further be broken down to
a)      Integer (%)
b)      Long integer (&)
c)      Single precision (!)
d)      Double precision (#)

String variable – A symbol or variable used to store string or strings is called a string variable.
The name of a string variable should start with a character and should end with a dollar ($) sign.

For example K$= “KATHMANDU
                     N$ =”NEPAL”

String – A group of letters or numbers or both which are enclosed within a pair of quotation marks ( “ “ ) is called a string.
For example “ HIMS “
            “ 123 HIMS “

Types of string data :
Qbasic supports two types of string data :
a)      Variable length string
b)      Fixed length string

Variable length string – It may store a string of different length, here, the length of string is not fixed. It can support from 0 to 32767 characters.

Fixed length string – a fixed length string has a declared length that remains fixed throughout the execution of the program.

Constant-  A symbol whose value does not change during the execution of the program is called a constant.
Types of constant :    i) numeric constant                 ii) string constant
Numeric constant – Constant whose value is numeric e.g. 899.50, -25.46, 97 etc. are numeric constant. Among these those with decimal is called numeric real constant, e.g 899.50, -25.46 etc. and those with integer only are called numeric integer constant, e.g. 97,-568, 4 etc.

String constant – A string constant is a text value that consists of alphabets, digits, symbols and other special characters.
Expression – An expression can be  a string or numeric constant, a variable or a combination of constants variable with operators.

Types of expression :

a)      Arithmetic expression – An expression which contains values, variables and operators that returns a single numeric value after operation is called arithmetic expression. For example let x= y+z

b)      Logical expression – A logical expression contains values and operations which returns one of two logical values ( true or false ) for example 6>5<7

c)      String expression – an expression which returns string value after processing strings with the help of string operators. For example PRINT A$ + B$

Operators- Operators are symbols representing valid operations on values.

Operand – Operands may be a constant value or variable on which mathematical and logical operations take place.
The following expression shows operands with an operator.
      OPERATOR

X = 7 + 9 

OPERANDS

Types of operators:
a)      Arithmetic operators
b)      Relation operators
c)      Logical operators
d)      String operators

Arithmetic operators – Arithmetic operators are used to solve the value of an expression. In Qbasic, the following arithmetic operators can be used.

Operators
Action
+
Addition
-
subtraction
*
multiplication
/
Division
^
To the power



Relational operators – Relational operators are used to compare two or more values. Using this, we can compare values of variables with a constant. In Qbasic the following relational operators can be used.

Operators
Relation
=
Equal to
<> 
Not equal to
Less than
<=
Less than equal to
Greater than
>=
Greater than equal to


Logical operators – Logical operators are used to examine two or more relations. The outcome of this examination is given in TRUE or FALSE. Logical operators most often used are AND, OR, and NOT.

Outcome table of AND operator
Condition
Outcome
I
II

TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE


Outcome table of OR operator
Condition
Outcome
I
II

TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE


Outcome table of NOT operator
Condition
Outcome
TRUE
FALSE
FALSE
TRUE

Statement – a collection of commands used in the lines of a program is called a statement. In Qbasic, the statements can be divided into four groups :
a)      Assignment statement
b)      Input / output statement
c)      Declaration statement
d)      Control statement

a)      Assignment statement – A statement used to assign value of a variable is called assignment statement.
For example let A =5
                        B = 7
                        D = A +B
                        PRINT D
                        END

SWAP statement – SWAP statement is used to exchange the values of two similar type of variables
Syntax – SWAP <variable 1><varaible2>
For example:
REM EXAMPLE OF SWAP
LET X = 100
LET Y = 200
PRINT “BEFORE SWAPPING DATA “;
PRINT X
PRINT Y
PRINT “AFTER SWAPPING DATA” ;
SWAP X , Y
PRINT X
PRINT Y
END

b)     Input / output statement – Input / output statements allow the user to input data to the computer and print the result after processing. They are used to perform input/output operations of a computer. Some common input/output statements are INPUT, LINE INPUT, PRINT, LPRINT etc.

CLS
Function – Clears the screen.

INPUT
Function – Reads input from the keyboard.

DATA
Function – Specifies values to be read by subsequent READ statements.

READ
Function – Reads those values and assigns them to variables.

RESTORE
Function – Allows READ to reread values in specified DATA statements.

INKEY$
Function – Reads a character from the keyboard.

TAB
Function – Moves the cursor to a specified print position

SPC
Function – Skips a specified number of spaces in a PRINT or LPRINT statement.

PRINT
Function – Writes data to the screen or to a file.

Declaration statement – A statement used to define or declare a constant, variable or array etc, is called declaration statement.
CONST, DIM, REM

CONST
Function – declares one or more symbolic constants.

DIM
Function – Declares an array or specifies data type for a non array variable.

REM
Function – Allows explanatory remarks to be inserted in a program.

Example of CONST and REM
REM TO CALCULATE AREA OF A CIRCLE
CLS
CONST PI =3.141593
INPUT “RADIUS OF CIRCLE”; R
PRINT “AREA = “ PI * R ^ 2
END


EXAMPLE OF DIM
DIM NAME$ (5)
FOR I = 1 TO 5
READ NAME$ (I)
PRINT NAME$ (I)
NEXT I
DATA NEPAL,INDIA,CHINA,BHUTAN,SRILANKA
END

Control flow statements – A statement which controls the program flow while executing the program instructions one after another is called control statement.
GOTO, IF …. END IF, FOR ….. NEXT etc. are few examples of control statements.

GOTO LINE
Function – Branches to a specified line.

Decision making statements:
1.      IF ….. THEN …. END IF
Function – This statement is used for making decisions and it also checks a single condition.
Syntax – IF <CONDITION> THEN
            <STATEMENTS>
            END IF

EXAMPLE:        CLS
                        LET C = 1
                        TOP :
                        PRINT C
                        LET C = C + 1
                        IF C < = 10 THEN
                        GOTO TOP
                        END IF
                        END


2.      IF …… THEN ….. ELSE ….. END IF
Function – This statement is used for making decisions and it checks double condition.
Syntax – IF <CONDITION> THEN
            <STATEMENT>
            ELSE
            <STATEMENT>
            END IF

            Example :        CLS
                                    INPUT “ENTER LENGTH”; L
                                    INPUT “ENTER BREADTH “; B
                                    LET A = L * B
                                    IF A > = 50 THEN
                                    PRINT “BIG”
                                    ELSE
                                    PRINT “SMALL”
                                    END IF
                                    END


3.      IF …. THEN …. ELSE IF
Function – This statement is used for checking multiple conditions
Syntax – IF <CONDITION> THEN
            <STATEMENTS>
             ELSE IF
            <STATEMENTS>
            ELSE
            <STATEMENTS>
            END IF

EXAMPLE ;
                        CLS
                        INPUT “ENTER PERCENTAGE “; P
                        IF P > = 60 THEN
                        PRINT “ 1ST. DIVISION”
            ELSE IF P >= 50 AND P < = 59 THEN
            PRINT “2ND DIVISION”
            ELSE IF P > = 40 AND P < = 49 THEN
            PRINT “3RD DIVISION”
            ELSE
            PRINT “FAIL “
            END IF
            END


4.      SELECT CASE …… END SELECT
Function – This command executes one of several statement blocks depending on the value of the expression.
Syntax :                        SELECT CASE TEXT EXPRESSION
                        CASE EXPRESSION LIST ONE
                        <STATEMENT BLOCK 1>
                        CASE EXPRESSION LIST2
                        <STATEMENT BLOCK 2 >
                        CASE ELSE
                        <STATEMENT BLOCK 3 >
                        END SELECT

EXAMPLE :
                        CLS
                        INPUT “ENTER NUMBER FROM 1 TO 10 “; N
                        SELECT CASE N
                        CASE 1,3,5,7,9
                        PRINT “THE NUMBER IS ODD”
                        CASE 2,4,6,8,10
                        PRINT “THE NUMBER IS EVEN”
                        CASE ELSE
                        PRINT “INVALID NUMBER “
                        END SELECT
                        END


5.      FOR ….. NEXT             
Function – Repeats a  block of statements a specified number of times.
Syntax -                       FOR <VARIABLE > = < 1 TO N ><STEP >
                        STATEMENTS
                        NEXT

EXAMPLE –      FOR I = 1 TO 10
                        PRINT I
                        NEXT
                        END    


6.      WHILE …. WEND
Function – This command executes a series of statements as long as the specified condition is true.
Syntax -           WHILE <CONDITION>
                        STATEMENTS
                        WEND
EXAMPLE –
                        CLS
                        X = 1
                        WHILE X <  = 10
                        PRINT X
                        X = X + 1
                        WEND
                        END


7.      DO …. LOOP
Function – This command repeats a block of statements while the condition is true or until the condition becomes true.
Syntax -                       DO <WHILE /UNTIL > CONDITION
                        STATEMENTS
                        LOOP
EXAMPLE –
                        X = 1
                        DO WHILE X < = 10
                        PRINT X
                        X = X + 1
                        LOOP
                        END


Write a program using WHILE …. WEND, DO …. LOOP and FOR …. Next to print numbers from 1 to 20.

            REM USING WHILE …. WEND
            CLS
            X = 1
            WHILE X < = 20
            PRINT X
            X = X + 1
            WEND
            END


REM USING DO …. LOOP
CLS
X=1
DO WHILE X < = 10
PRINT X
X = X + 1
LOOP
END


REM USING FOR …. NEXT
CLS
FOR X =  1 TO 20
PRINT X
NEXT
END


Write a program to generate the following series 2,4,6,8 up to 10th term using WHILE …. END, DO …. LOOP and FOR ….. NEXT statements.

REM USING WHILE … WEND
CLS
X = 2
WHILE X < = 20
PRINT X
X = X + 2
WEND
END


REM USING DO …. LOOP
CLS
X =2
DO WHILE X < = 20
PRINT X
X = X + 2
LOOP
END


REM USING FOR …. NEXT
CLS
FOR X = 2 TO 20
PRINT X
X = X + 1
NEXT
END


Write a program to generate the following series 2,2,4,6,10 up to 10th term using WHILE … WEND.

REM USING WHILE …. WEND
CLS
A = 2
B = 2
X =1
C = 0
 PRINT A,B
WHILE X < = 15
C = A + B
PRINT C
SWAP A , B
SWAP B , C
X = X + 1
WEND
END


QBASIC – QBASIC stands for Quick Beginners All Purpose Symbolic Instruction Code. It is the most popular high level programming language used by the beginners to write and develop elementary programs.
The original BASIC programming language was developed by Thomas Kurtz and John Kemeny in the year 1963 -1964.

Loop – In programming repeated execution of a sequence of statements is called a loop or looping.

Nested loop – A loop within a loop is called a nested loop.

Termination – Ends or terminates a basic program or a procedure.

Bug – An error or fault present in a program is called a bug.

De-bug (debugging) – The process of finding and correcting the bug (error) in a program is called debugging.

Counter – This is a variable in which the count of number of occurrences of certain event is stored while executing the program.

Accumulator – Any variable in which results of mathematical calculations are stored while the execution of the program goes on is called accumulator.

Flag – An indicator which is set or unset depending upon the condition of the program is called a flag.

Indentation – Indentation should be followed while writing computer programs. This helps in understanding the program command, minimizes bugs and makes the debugging easy.

Branching (jumping) – If the execution of any program depart conditionally or unconditionally from its sequential flow depending on the result of a test, it is called branching.


String operators / manipulators functions -  String represents alpha numeric characters (combination of alphabets and numbers that are enclosed within quotation marks).

Qbasic has many string functions that can be applied to strings and to modify and alter them if necessary. These are called string a manipulators. Since, they manipulate or re-arrange values within a string.

1.      ASC
Function – ASC returns the ASCII code for the first character in string expression.
Syntax – ACS (string expression $ )


2.      CHR$
Function – CHR$ returns the character corresponding to a specified ASCII code.
Syntax – CHR$ (ascii code %)

EXAMPLE :
REM EXAMPLE OF ASC AND CHR$
PRINT ASC( “Q”)
PRINT CHR$ (65)
END


3.      LEFT$
Function – Returns a specified number of leftmost characters in a string.
Syntax – LEFT$ ( string expression $, n%)


4.      RIGHT$
Function – Returns a specified number of rightmost characters in a string.
Syntax – RIGHT$ ( string expression $, n%)

EXAMPLE :
REM EXAMPLE OF LEFT$ AND RIGHT$
SUB$ = “COMPUTER SCIENCE”
PRINT LEFT$ (SUB$, 8)
PRINT RIGHT$ (SUB$, 7)
END


5.      MID$
Function – The MID$ function returns part of a string (a substring)
Syntax – MID$ (string expression$, start %, length %)

EXAMPLE :
REM EXAMPLE OF MID$
TOPIC$ =  “COMPUTER IS FUN”
PRINT MID$ (TOPIC$, 1, 8)
PRINT MID$ (TOPIC$, 13, 3)
PRINT MID$ (TOPIC$, 4, 3)
END


6.      LEN
Function – Returns the number of characters in a string or the number of bytes required for storing a variable.
Syntax – LEN (string expression $)

EXAMPLE :
REM EAMPLE OF LEN
SUB$ = “COMPUTER SCIENCE”
PRINT LEN (SUB$)
ANUM = 2345.45
PRINT LEN (ANUM)
END


7.      LTRIM$
Function – Remove leading spaces from a string.
Syntax – LTIM$ (string expression$)


8.      RTRIM$
Function – Remove trailing spaces from a string.
Syntax – RTRIM$ (string expression$)

EXAMPLE :
REM EXAMPLE OF LTRIM$ AND RTRIM$
SUB$ = “    QBASIC”
PRINT”*” + SUB$ + “*”
PRINT “*” + LTRIM$ (SUB$) + “*”
PRINT”*” + RTRIM$ (SUB$) + “*”
END


9.      STR$
Function – Returns a string representation of a number.
Syntax – STR$ (numeric expression)


10.  VAL
Function – Converts a string representation of a number to a number
Syntax – VAL (string expression$)

EXAMPLE :
REM EXAMPLE OF STR$ AND VAL
PRINT “DECIMAL 65 IS REPRESENTED IN HEXADECIMAL AS”;
PRINT “8H” + LTRIM$ (STR$ (41))
PRINT VAL (RIGHT$ (“NEW YEAR”, 4))
END


11.  SPACE$
Function – Returns a string of spaces.
Syntax – SPACE$ (N%)

Example:
REM EXAMPLE OF SPACE$
FOR I% = 1 TO 5
X$ = SPACE$ (I%)
PRINT X$, I%
NEXT I%
END


12.  STRING$
Function – Returns a string of a specified length made up of a repeating character.
Syntax – STRING $ (LENGTH% { ASCII-CODE %) STRING EXPRESSION $ })

EXAMPLE:
REM EXAMPLE OF STRING$
PRINT STRING$ (9, “*” )
PRINT “* HELLO * “
PRINT STRING$ (9, “*”)
END


13.  LCASE$
Function – converts strings to all lowercase letters.
Syntax  - LCASE$ (STRING EXPRESION $)


14.  UCASE$
Function – converts strings to all uppercase letters.
Syntax – UCASE$ (STRING EXPRESSION$)

EXAMPLE :
REM EXAMPLE OF LCASE$ AND UCASE$
TEXT$ = “ KATHMANDU “
PRINT LCASE$ (TEXT$)
PRINT UCASE$ (TEXT$)
END

15.  INSTR
Function – Returns the position of the first occurrence of a string in another string.
Syntax – INSTR ([START%] STRING EXPRESSION 1$, STRING EXPRESSION 2$)

EXAMPLE:
REM EXAMPLE OF INSTR
A$= “MICROSOFT QBASIC”
PRINT “STRING POSITION =”: INSTR (1, A$, “QBASIC”)
END


16.  DATE$
Function – Returns and sets the computers current system date.
Syntax – DATE$ = STRING EXPRESSION$

EXAMPLE:
REM EXAMPLE OF DATE$
PRINT DATE$
DATE$ = “01-01-14”
PRINT “DATE SET TO “; DATE$
END


17.  TIME$
Function – Returns and sets the current system time on your computer.
Syntax – TIME$ = STRING EXPRESSION$

EXAMPLE:
REM EXAMPLE OF TIME$
PRINT TIME$
TIME$ = “09-11-54”
PRINT “TIME SET TO “; TIME$
END


Mathematical Calculation Functions

1.      ATN
Function – ATN returns the arctangent of a specified numeric expression.
Syntax – ATN ( numeric expression )

2.      COS
Function – COS returns the cosine of a specified angle.
Syntax – COS (angle)

3.      SIN
Function – SIN returns the sine oaf a specified angle
Syntax – SIN (ANGLE)

4.      TAN
Function – TAN returns the tangent of a specified angle.
Syntax – TAN (angle)

EXAMPLE:
REM EXAMPLE OF ATN, COS, SIN AND TAN
CLS
CONST PI = 3.1415926
PRINT ATN (TAN(PI/4!)), PI/4!
PRINT (COS (180 * (PI / 180)))
PRINT (SIN ( 90 * ( PI /180 )))
PRINT ( TAN (45 * (PI / 180 )))
END

5.      MOD
Function – Divides one number by another and returns the remainder.
Syntax – numeric expression 1 mod numeric expression 2

EXAMPLE :
REM EXAMPLE OF MOD
PRINT 27 MOD 4.6
END

                        
6.      SQR
Function – Returns the square root of a numeric expression
Syntax – SQR (numeric expression)

7.      ABS
Function – ABS returns absolute value of a number.
Syntax – ABS (numeric expression)

8.      SGN
Function – SGN returns absolute a value indicating the sign of a numeric expression.
Syntax – SGN (numeric expression)

EXAMPLE
REM EXAMPLE OF ABS/SGN
PRINT SQR (9)
PRINT ABS (55.5-100!)
PRINT SGN (15), SGN (-12),SGN (0)
END

9.      CINT
Function – CINT rounds a numeric expression to an integer.
Syntax – CINT (numeric expression)

10.  CLNG
Function – CLNG rounds a numeric expression to a long 4 byte integer.
Syntax – CLNG (numeric expression)

EXAMPLE:
REM EXAMPLE OF CINT/CLNG
PRINT CINT (12.49), CINT (12.51)
PRINT CLNG (338457.8)
END

11.  FIX
Function – FIX truncates a floating point expression to its integer position.
Syntax – FIX (numeric expression)

12.  INT
Function – INT returns the largest integer less than or equal to a numeric expression.
Syntax – INT (numeric expression)

EXAMPLE:
REM EAMPLE OF FIX / INT
PRINT FIX (100.34), FIX (-37.25), FIX(.8755)
PRINT INT (8.952),INT(1.9),INT(-7.001)
END




CONCEPT OF MODULAR PROGRAMMING

FUNCTION:
A function in QBASIC is a readymade program or user made (small) program which helps to perform a specific task.

TYPES OF FUNCTIONS:
QBASIC supports two types of function:
a)      User defined function
b)      Library function

a)      User defined function:
A user defined function is created by a user whenever the user needs to perform a certain task that cannot be performed by using a library function. ( a user defined function is created by using FUNCTION ….. END FUNCTION statement)

b)      Library function:
Library functions are the ready- made programs that accept data and returns a value.
These functions are written by the developer of QBASIC at the time of development of QBASIC. Library functions are also called routine functions or built-in-functions.
The two commonly used library functions are:
i)                    String functions/manipulators (e.g. LEN, RIGHT$, MID$ etc)
ii)                   Mathematical functions (e.g. ABS, INT, MOD etc)

Linear programming:
When a program becomes complex and unmanageable, this type of programming structure is called linear programming.

Modular programming:
The way of writing a program by breaking the complex program into small, logical and manageable part is known as modular programming.

Module/Procedure:
The small logical and manageable part of the program is called a module or procedure, which sometimes are also referred as a sub program or a sub module, that contains codes i.e. instructions for performing a certain task.
(since the modular programming uses small block of functional codes it is also called structured programming)

Advantages of procedure/module:
a)      A procedure can be reused more than once without rewriting it, so it reduces the length of a program
b)      The procedures can be tested and debugged separately.
c)       Improves the readability of the program.
Note : A modular program has a main module and may have many sub-modules. The main module contains the entry and ending point of the program. The statements or codes written in a main module are known as module level codes.

Concept of passing parameters/arguments to a function or procedure:
There are two ways to pass parameters to a function or procedure. They are:
a)      Passing by value
b)      Passing by reference

a)      Passing by value: When arguments are passed by value , it does not make any effect to the value of the variables which are passed to a procedure even if they are changed in the procedure. ( to pass arguments by value method each argument is enclosed in individual parenthesis in the calling statement )

b)      Passing by reference: The address of the variables are passed to the procedure, that is the parameter uses the memory location of the argument. If the value of variable is changed in the procedure then it changes the value of the variable in the main module.

Concept of local and global variable
Local variable: A variable which is declared inside a module and which cannot be accessed by all the modules is known as local variable.
( All variables that is declared implicitly or explicitly without using SHARED attribute are local variables )

Global variable: A variable in main module which can be accessed from any sub module or a procedure of a program is known as global variable.
( a global variable is declared in the main module by using DIM or COMMON statement with SHARED attribute ) 
Example:     COMMON SHARED <VARIABLE LIST>
                        DIM SHARED <VARIABLE LIST>

Types of procedure:
There are two types of procedure:
a)      FUNCTION procedure
b)      SUB procedure

FUNCTION Procedure: A FUNCTION procedure performs the specific task and returns a value to the main program. To use the FUNCTION procedure it is needed to CALL. Since a function procedure returns a value, it is called either by using PRINT statement or storing a returned value into a variable.

A FUNCTION procedure is defined by using FUNCTION ……. END FUNCTION

Syntax – FUNCTION NAME <PARAMETERLIST>
                < STATEMENTS >
                NAME = <EXPRESION>
                END FUNCTION

NAME = Where NAME is a name of a FUNCTION procedure . The rule for naming a function is the same as rules for naming a variable.
Since a function returns a value, a function may be a string or numeric. A string function name is followed by the type declaration symbol dollar ($) whereas numeric function name may be followed by either %, &, !Or # symbol.

Parameter list: parameter list is the list of variables that accepts the values, passes to it when the function is called. Each variable or constant is separated by commas.
Expression: Expression is the value that has to be returned to the calling module.

DECLARE:
Function-Declares a FUNCTION or SUB procedure and invokes argument, data type checking.
Syntax – DECLARE {FUNCTION/SUB} NAME (PARAMETER LIST) 


Example 1.  Program to find the sum of two values using FUNCTION …… END FUNCTION
DECLARE FUNCTION SUM ( A, B )
CLS
INPUT “ ENTER THE FIRST VALUE”; A
INPUT “ENTER THE SECOND VALUE”;B
PRINT” THE SUM OF TWO VALUES”; SUM (A,B)
END

FUNCTION SUM (A,B)
SUM= A+B
END FUNCTION

Example 2. Program to find the average of two values
DECLARE FUNCTION AVG ( X, Y )
CLS
INPUT “ ENTER THE FIRST VALUE”; X
INPUT “ENTER THE SECOND VALUE”;Y
PRINT” THE AVERAGE OF TWO VALUES”; AVG (X,Y)
END

FUNCTION AVG (X,Y)
AVG= (X+Y)/2
END FUNCTION

SUB Procedure:
A SUB procedure is a small logical and manageable part of a program which performs the specific task and does not return any value. A SUB procedure is called by using the CALL statement.
A SUB procedure is defined by using SUB ……. END SUB statement.

SUB …….. END SUB
Function : The SUB statement is used to define a sub procedure.
Syntax: SUB NAME <PARAMETERLIST>
                STATEMENT BLOCK
                END SUB

CALL:
Function: Transfers control to a SUB procedure.
Syntax : CALL NAME <PARAMETERLIST>
Example 1. Program to find the sum of two values using SUB …… END SUB


REM PARAMETER PASSING BY REFERENCE
DECLARE SUB SUM (A,B)
CLS
INPUT “ENTER FIRST VALUE”;A
INPUT”ENTER SECOND VALUE”;B
CALL SUM (A,B)
END

SUB SUM (A,B)
SUMT=A+B
PRINT “THE SUM OF TWO VALUES”;SUMT
END SUB

Example 2. Program to find the sum of two values using SUB …… END SUB
REM PARAMETER PASSING BY VALUE
DECLARE SUB SUM (A,B)
CLS
CALL SUM (7,9)
END

SUB SUM (A,B)
SUMT=A+B
PRINT “THE SUM OF TWO VALUES”;SUMT
END SUB


Example 3. Program to find the average of two values
DECLARE SUB AVG ( X, Y )
CLS
INPUT “ ENTER THE FIRST VALUE”; X
INPUT “ENTER THE SECOND VALUE”;Y
CALL AVG (X,Y)
END

SUB AVG (X,Y)
AVGT= (X+Y)/2
PRINT “THE AVERAGE OF TWO VALUES”; AVGT
END SUB





i)            Sample Programs using FUNCTION ….. END FUNCTION:
1.       Program to find the circumference of a circle

DECLARE FUNCTION CIRC(R)
CLS
INPUT  “ENTER THE RADIUS OF THE CIRCLE”; R
PRINT ” THE CIRCUMFERENCE OF THE CIRCLE”; CIRC(R)
END

FUNCTION CIRC(R)
CIRC = 2*3.14*R
END FUNCTION


2.       Program to find the area of a rectangle
DECLARE FUNCTION RECT ( L,B)
CLS
INPUT “LENGTH OF RECTANGLE”; L
INPUT BREADTH OF RECTANGLE”;B
PRINT” THE AREA OF RECTANGLE”; RECT(L,B)
END

FUNCTION AREA (L,B)
AREA = L*B
END FUNCTION

3.       Program to find the volume of a cylinder

DECALRE FUNCTION VOL (R,H)
CLS
INPUT “INPUT RADIUS”;R
INPUT “INPUT HEIGHT”;H
PRINT” THE VOLUME OF CYLINDER”; VOL(R,H)
END

FUNCTION VOL (R,H)
VOL=3.14*R^2*H
END FUNCTION

ii)                  Sample Programs using SUB ….. END SUB:

1.       Program to generate the 1,1,2,3,5 series upto 10th term.

DECLARE SUB XYZ ()
CLS
CALL XYZ
END

SUB XYZ
X=1
Y=1
FOR I= 1 TO 10
PRINT X
Z=X+Y
X=Y
Y=Z
NEXT
END SUB

2.       Program to generate the following series 5,10,15,20 upto 10th term

DECLARE SUB SERIES ()
CLS
CALL SERIES
END

SUB SERIES
N=5
FOR I= 1 TO 10
PRINT N
N=N+5
END SUB

3.       Program to generate the following series 2,22,222 upto 10th term

DECLARE SUB SERIES
CLS
CALL SERIES
END

SUB SERIES
N=2
FOR I=1 TO 10
PRINT N
N=N*10+2
END SUB

4.       Program to  generate Armstrong number between 1 to 100

DECLARE SUM ARM (A,B)
INPUT “ENTER THE NUMBER/ THE LARGEST NUMBER IS 100”; N
FOR I = 1 TO N
A = I
CALL ARM (A,B)
IF B = I THEN
PRINT B
END IF
NEXT I

SUB ARM (A,B)
S = 0
WHILE A <> 0
R = A MOD 10
S =S + R ^ 3
A = A\10
WEND
B = S
END SUB



Examples of programs using string manipulators:

a.       Program to reverse a string which is passed as a parameter using SUB… END SUB

DECLARE SUB REV (N$)
N$=”NEPAL”
CALL REV (N$)
END

SUB REV (N$)
FOR I = LEN (N$) TO 1 STEP -1
R$ = MID$ (N$, I, 1)
PRINT R$
NEXT I
END SUB


b.      Program to reverse a string which is given (input) by the user.

DECLARE SUB REV (W$)
CLS
INPUT”ENTER A STRING”; W$
CALL REV (W$)
END

SUB REV (W$)
FOR I = LEN(W$) TO 1 STEP -1
R$ =  MID$ (W$, I, 1)
PRINT R$
NEXT I
END SUB

c.       Program to check the entered string is  Palindrome or not.

DECLARE SUB PAL (S$)
CLS
INPUT”ENTER A STRING”; S$
REV$ = PAL (S$)
IF REV$= S$ THEN
CALL PALL (S$) ELSE
PRINT “ THE WORD IS NOT A PALINDROME”
END

SUB PAL (S$)
L= LEN (S$)
FOR I = L TO 1 STEP -1
REV$ = REV$ + MID$ (S$, I, L)
NEXT I
PAL$ = REV$
PRINT “THE WORD IS A PALINDROME”
END SUB

d.      Program to find vowels from a entered word

DECLARE SUB VOWEL (V$)
CLS
INPUT “ENTER A STRING”; V$
CALL VOWEL (V$)
END

SUB VOWEL (V$)
L = LEN (V$)
FOR I = 1 TO L
CH$ = MID$ (V$, I, L)
IF CH$ = “A” OR CH$= “a” OR CH$ = “E” OR “e” OR CH$ = “I” OR CH$ = “i” OR CH$ = “O” OR CH$ = “o” OR CH$ = “U” OR CH$ =”u” THEN
PRINT CH$;
END IF
NEXT I
END SUB


e.      Program to find consonant from a entered word

DECLARE SUB XYZ
CLS
CALL XYZ
END

SUB XYZ
INPUT “ENTER A WORD”; W$
FOR I = 1 TO LEN (W$)
X$ = MID$ (W$, I, 1)
X$= UCASE$(X$)
IF X$ <> “A” AND X$ <> “E” AND X$ <> “I” AND X$ <> “O” AND X$ <> “U” THEN
C = C+1
NEXT
PRINT “TOTAL CONSONANT = “ ;C
END SUB



*** Examples of General programs***

a)      Program to convert Celsius to Fahrenheit where F = (9/5 * C ) + 32

DECLARE SUB CTOF ( C )
CLS
INPUT “ ENTER DEGREE IN CELSIUS “; C
CALL CTOF ( C )
END

SUB CTOF ( C )
F = (9 * C /5 ) + 32
PRINT “ IN FAHRENHIET “ ; F
END SUB



b)      Program to calculate simple interests

DECLARE SUB SIM (P,T,R,)
CLS
INPUT “ ENTER PRINCIPAL AMOUNT”; P
INPUT “ENTER TIME”; T
INPUT “ENTER RATE”; R
CALL SIM (P,T,R)
END

SUB SIM (P,T,R)
SI = ( P*T*R )/100
PRINT “SIMPLE INTEREST =”; SI
END SUB


Concept of Array:
Array – Array permits us to represent a list of values with one variable name.
A particular quantity is indicated by writing a subscript in the parenthesis after the variable.
The complete set of quantities is called an array, and the individual quantities are called the elements. A subscript is called an index.

Types of array
a) One or single dimensional array
b) Two Dimensional  Array:

Example:
DIM X(5)
FOR I = 1 TO 5
READ X ( I )
PRINT X
NEXT I
DATA 19,17,11,3,-5
END




File processing /File Handling in QBasic

Types of files in QBasic
a.       Program file
b.      Data file

Program file: A program file has a set of instruction that is needed for processing data whatever tasks needs to be performed that is done by executing a program file. Program files do not store data for future use.

Data file: A data file is a collection of related data stored in a secondary storage. In order to store the output of the program in the disk for later use, data file needs to be created using a program.

Types of data files
Depending on the way in which the data is stored and accessed. Data files are categorized as:
i.                     Sequential access file
ii.                   Random access file

Sequential access file: In a sequential access data file, data are stored in sequential order. The data of a sequential access file can only be accessed sequentially.

Disadvantages of sequential access file.
a.       A particular record of a file cannot be accessed directly. So the time taken to access the data is longer.

Random access file :A user can read or write any record directly in a random access file. Thus, reading and writing of data is faster compared to sequential access file.

Opening a data file
Points  to remember
        I.            A sequential data file is needed to open before it can be used.
      II.            Opening of a data file could be for different purposes such as:
a.       To write data
b.      To read data
c.       To delete or add some more data etc.
As the requirement, a sequential files need to be opened in different mode. The different mode and their purpose are as follows.
 MODE
Purpose
OUTPUT
To create a new data file and write data.
INPUT
To retrieve or read the contents of an existing data file.
APPEND
To add more records in the existing data file






File-Input-Output Statements
The commands under this group enables us to save data to a file. So that the file can be retrieved later, for printing, adding more data at the end of the file or for modifying the saved data.

The commands under Input/Output files are :
a.       OPEN
b.      OUTPUT
c.       INPUT
d.      APPEND
e.      LINE INPUT
f.        WRITE
g.       CLOSE
h.      EOF

OPEN
FUNCTION – Open a file or device.
Syntax – Open <File name> FOR <MODE>AS # FILENUMBER

OUTPUT
FUNCTION- To create a new data file and write data.
Syntax: OPEN <FILENAME> FOR <OUTPUT>AS  # FILENUMBER

INPUT
FUNCTION : Reads the input from the keyboard or a file.
Syntax: Open < FILE NAME > FOR < INPUT>AS # FILENUMBER

APPEND
FUNCTION : Allows to add records to an existing data file.
Syntax : OPEN < FILENAME> FOR < APPEND> AS # FILENUMBER

LINE INPUT
FUNCTION : It reads a line of up to 255 characters from a keyboard or a file.
Syntax :  LINE INPUT # Filename %, Variable $

WRITE
FUNCTION- It writes data to a string or a sequential file.
Syntax- WRITE # FILENUMBER%, expression list.

CLOSE
FUNCTION- This command closes one or more open files or devices. CLOSE without any argument closes all open files and devices.
Syntax- CLOSE # FILENUMBER, FILENUMBER n

EOF
FUNCTION- EOF test for the end of a file. EOF returns true if the end of the file has been reached.
Syntax- EOF (FILE NUMBER %)

File System Commands
1.       CHDIR
FUNCTION- Changes the drive’s default directory.
Syntax- CHDIR PATHNAME$


2.       MKDIR
FUNCTION- Creates a sub- directory.
Syntax- MKDIR PATHNAME$

3.       RMDIR
FUNCTION- Removes a sub- directory.
Syntax- RMDIR PATHNAME$

4.       FILES
FUNCTION- Displays the contents of the current directory, or a specified directory.
Syntax- FILES [FILESPEC$]

5.       NAME
FUNCTION- Renames a file or directory.
Syntax- REN OLDSPEC$ AS NEWSPEC$

6.       KILL
FUNCTION- Deletes a file from disk.
Syntax- KILL FILESPEC$

7.       RUN
FUNCTION- Executes a current program or a specified program.
Syntax- REN [LINE NUMBER / FILE$]


8.       SYSTEM
FUNCTION- Closes all open files and returns control to the operating system.
Syntax- CHDIR PATHNAME$

9.       SHELL
FUNCTION- Suspends execution of a QBASIC program to run a DOS command or a batch file.
Syntax- SHELL COMMAND STRING$
1.      

      Program to create a sequential data file “STUDENT.DAT” to store students name, address and telephone no.

REM TO CREATE AN INPUT FILE
OPEN “STUDENT.DAT” FOR OUTPUT AS #1
CLS
DO
INPUT “STUDENTS NAME”; N$
INPUT “STUDENTS ADDRESS”; A$
INPUT “TEL NO”; T
WRITE #1, N$, A$, T
INPUT “WANT TO CONTINUE Y/N” ; CH$
LOOP WHILE CH$ =”Y” OR CH$ = “y”
CLOSE #1
END


2.       Program to read and display records from the file “STUDENT.DAT”.

REM TO CREATE AN OUTPUT FILE
OPEN “STUDENT.DAT” FOR INPUT AS #1
CLS
PRINT “NAME”, “ADDRESS”, “TEL NO”
DO WHILE NOT EOF (1)
INPUT #1, N$, A$, T
PRINT N$, A$, T
LOOP
CLOSE #1
END


3.       Program to display only those records whose address is Kathmandu.

OPEN “STUDENT.DAT” FOR INPUT AS #1
CLS
PRINT “NAME”, “ADDRESS”, “TEL NO”
DO WHILE NOT EOF(1)
IF A$ = ”KATHMANDU” THEN
INPUT #1, N$, A$, T
PRINT N$, A$, T
END IF
LOOP
CLOSE #1
END


4.       Program to add more records to the file “STUDENTS.DAT”

OPEN “STUDENTS.DAT” FOR APPEND AS #1
CLS
DO
INPUT “STUDENTS NAME”; N$
INPUT “STUDENTS ADDRESS”; A$
INPUT “TEL NO”; T
WRITE #1, N$, A$, T
INPUT “WANT TO CONTINUE Y/N” ; CH$
LOOP WHILE CH$ =”Y” OR CH$ = “y”
CLOSE #1
END


Programming concept questions.

1.       What is a programming language – 8

2.       What is a program- 5

3.       Define an algorithm-5

4.       What is a flowchart -4

5.       What is Qbasic-12

6.       What are the data types used in Qbasic- 4

7.       Define a constant and mention its types-7

8.       What is a variable-7

9.       Mention the types of variables-5

10.   Differentiate between string and numeric variable-6

11.   What is a string-7

12.   Define operands-7

13.    What are operators? Mention its types-8

14.   Mention the types of logical operators-5

15.   Define with example string operators-8

16.   Define a loop-5

17.   What is a nested loop-4

18.   What is a bug-4

19.   What is debugging-5

20.   What is a counter-5

21.   Define an accumulator-6.

22.   What is a statement? Mention its types-12

23.   What is a function-5

24.   Mention the types of functions-4

25.   What is a library function-12

26.   What is a user defined function-8

27.   Define linear programming-6

28.   What is modular programming-6

29.   What is a module/procedure-9

30.   Write two advantages of a module-8

31.   What is a local variable-5

32.   Define a global variable-6

33.   What are the types of procedures-4

34.   Define a function procedure-12

35.   Define a sub procedure-8

36.   Differentiate between function and sub procedure-8

37.   What is a parameter (list)-6

38.   Define argument-6

39.   Write the function of DECLARE and CALL statements-7

40.   What are the types of files used in Qbasic-4

41.     Mention one disadvantage of sequential access file-5

42.       What is a random access file-7

43.       Write the functions of the following file system commands: (3)

                                            I.            CHDIR

                                          II.            MKDIR

                                        III.            RMDIR

                                        IV.            FILES

                                          V.            NAME

                                        VI.            KILL

                                      VII.            RUN

                                    VIII.            SYSTEM

                                        IX.            SHELL

                                          X.            EOF






















Comments

Popular posts from this blog

Introduction to C

Grade8 Programming Concepts