Starting, Structure, Constants and Variables of QBASIC
QBASIC Programming
QBASIC is the most popular high level programming language. Various versions of BASIC have been developed by Microsoft Company. This language is quite simple to understand and has been adopted by most of the microcomputers. It is suitable for both mathematical and business problems. It is compatible with MSDOS environment and it has two basic files QBASIC.EXE and QBASIC.HLP. We can edit, debug and execute the program using these two files.
The advantages of QBASIC
1. QBASIC is easy to learn and fun to practice. It may be called a "People's language".
2. It is available almost in every computer from micro to mainframe. Therefore, a program developed in a micro can run on bigger system with minor modifications.
3. It is suitable for mathematical and business application.
4. Program development cycle is quick, debugging is simple, and
5. Modification of program is quite easy.
Starting QBASIC
It occupies very low memory so it may be possible to run the system using floppy disk also. It is compatible with MS-DOS and have only two files QBASIC.EXE and QBASIC.HLP.
Steps
1. Get MS-DOS System and MS-DOS Prompt
C:\>
2. Change the Directory
C:\>CD QBASIC
C:\QBASIC>
3. Type QBASIC and press Enter
C:\QBASIC>QBASIC enter
When you are working with Windows system. Open QBASIC Folder on Windows.
Double click over the QBASIC.EXE icon. We will get the QBASIC System as below. Press ESC key and get the programming window of the QBASIC and type the program on the working of QBASIC.
Structure of Basic
To construct the QBASIC program we have to arrange some standard elements.
The elements are:
1. Character set
2. Variables and constant
3. Arithmetic expressions
4. Relational or Logical expressions
5. Keywords
6. Syntax
7. Library functions
The Character Set
QBASIC has the character set consisting of the following elements:
1. Alphabets: A, B, C,....Z
2. Digits: 0, 1, 2........,9 and
3. Special characters: + - * / ( ) . , $ ; ,: ,= ,> ,< , ^ The symbol ^ (caret) is used to denote exponentiation operator, the symbol * (asterisk) is used to denote multiplication and other symbols; have their usual meanings. Constants and Variables A quantity in a computer program which does not change its value during the execution of the program is called a constant and the quantity which may change its values during the execution of the program is called variable. QBASIC allows the following constants: • Numeric constant Numeric constant is one that is formed by a sequence of digits 0, 1, 2,.....9 and may include a decimal point. A numeric constant known as number may be integer or a real number. 383, +57, 0, -6.2 and 6.15E4 are valid numeric constants. The number 6.15E4, in fact represent 6.15 * 104. The notation E is used to represent exponential form. The number after E is the exponent which can be positive or negative. However, its length cannot exceed two digits. It is also important to keep in mind that o QBASIC does not distinguish between an integer and fraction. o Commands are not allowed in a numeric constant. o The limit on the number of digits that can be used varies from computer to computer. Normally, a numeric constant can have up to a maximum of eight digits. • String constant A string constant consists of a sequence of characters which must be enclosed by a quotation mark. Simply defined, variable is a name, which can contain a value. Programming involves giving values to these names and presenting them in some form to the user. A variable has a type, which is defined by the kind of value it holds. In QBASIC, variables are also of two types: 1. Numeric variable :Numeric variable can assume numeric value and is represented by an alphabet or an alphabet followed by another alphabet or digit. For example A, C, A2, ABC, A6 etc, represent numeric variables. 2. String variable : A string variable is represented by an alphabet followed by dollar ($) sign. It should be kept in mind that while constructing the string variable, dollar ($) should be the last character. For example B1$, NAME$, BOOK1$, etc are valid string variables. There are two methods of telling the computer what kind of variable you are using: One-way is to just use the variable. This is called implicit declaration. Another way is to declare the variable AS a type, which can be done by using the DIM statement. E.g. a variable called number, which would contain an integer (whole number, no digits after the decimal point) is defined as: DIM number AS INTEGER Then you would use that variable as an integer. The word DIM actually originates from the word Dimension, it will be clear when we discuss arrays. This is called explicit declaration. We can put a symbol after the variable name, which is defined as representing that type. QBasic has a set of symbols, which represent each variable type: $ String % Integer & Long ! Single # Double Appending one of these symbols to the name of a variable when you use it in the program tells the computer that you are using it as that type. If we don't define the type of the variable, then QBasic assumes it is of the Single Precision type, which can often yield unexpected results. Type of variable Number / Characters Memory Example String 0 to 32767 character 1 Byte of each character A$ Integer A whole number – 32767 to 32767 2 Bytes A% Long Integer A whole number- 2 and more than 2 billion 4 Bytes A& Single precision A number with up to 7 digits after decimal point 4 Bytes A! Double precision A number with up to 15 digits after decimal point 8 Bytes A# The DIM statement is used to declare variables as follows: DIM state AS STRING DIM number AS INTEGER DIM profit AS DOUBLE DIM gpa AS SINGLE Some valid an invalid numeric variable names are provided below: Valid Numeric Variable Names firstTest profit& gpa! total.Price company8 COURSE2D Invalid Numeric Variable Names 1stClass --> (must begin with letter)
total Price --> (no spaces)
name,First --> (no commas)
Arithmetic, Relational or Logical Expression
Various symbols used to perform arithmetic and logical operations in programming language.
E.g., 18 + 56, in this + is the operator and 18 and 56 are operand.
Eg., A – B < C, in this – and < are the operators and A, B and C are operand. In any programming language value of arithmetic or logical operations are tested by using various operator symbols. Operators can be classified in 4 types. Arithmetic Operators Relational Operators Logical Operators and String Operators Arithmetic Expressions QBASIC can handle arithmetic expression involving the following arithmetic operators: Operator Meaning Example + Addition A + B OR 10 + 5 =15 - Subtraction C – D OR 30 – 23 =7 * Multiplication P * Q or 12 * 5 = 60 / Division R / S OR 7 / 2 = 3.5 \ Integer Division R\S OR 7\ 2 = 3 MOD Modulus Division 5 MOD 2 = 1 ^ To the power X^2 or 6^2 = 36 In addition to this hierarchy of operations, the following rules must be kept in mind in arithmetic expression: • Two operations must not appear together. For example, C+-D, A/-C, etc are not permitted. • String constants and string variables should not be used in arithmetic expressions. For example P+P$ is wrong. • When brackets are used, they must be used in pairs, i.e. every left bracket must be matched with a right bracket. • Denominator of an expression should not be zero. • Within a given pair of parentheses, the natural hierarchy of operations will apply. Relational or Logical Expressions Relational Operator Meaning = Equal to > Greater than
< Less than <= Less than or equal to >= Greater than or equal to
<> Not equal to
A relational expression is formed by using any of the following relational operators. Relational operators are used to compare two or more values. Using this we can compare value/s of variable/s with a constant. In QBASIC the following relational operators can be used.
When expressions are used on either side of relational operators, the expressions will be evaluated first and then the results of expressions compared. This means that relational operators come last in hierarchy of operators.
Logical operators
QBASIC, also supports logical operators to perform logical operation on numerical values. Logical operators are used to connect two or more relations and return a TRUE or FALSE value to be used in a decision.
The common logical operators are:
• AND Conjunction
• OR Disjunction
• NOT Logical Negation
For example, the expression A>50 AND B>150 is TRUE when A is more than 50 and at the same time B is more than 150.
Logical operators return results as indicated in the following tables. T indicates a TRUE and F indicates FALSE. X and Y are relational expressions.
AND Operator OR Operator
X Y X AND Y
T T T
T F F
F T F
F F T
X Y X OR Y
T T T
T F T
F T T
F F F
X NOT X
T F
F T
NOT Operator
String Operator:
A string expression consists of string constants, string variables and other string expressions combined by string operators.
There are two classes of string operations: concatenation and string function. The act of concatenating two strings is called concatenation. The plus (+) symbol is the concatenation operator for strings.
For example, the following program fragment combines the string variables A$ and B$ to produce the value FILENAME:
A$ = "FILE": B$ = "NAME"
PRINT A$ + B$
PRINT "NEW " + A$ + B$
Output:
FILENAME
NEW FILENAME
All string constants used in comparison expressions must be enclosed in quotation marks.
The following are examples of true string expressions:
"AA" < "AB" "FILENAME" = "FILE"+"NAME" "X&" > "X#"
"CL " > "CL"
"kg" > "KG"
"SMYTH" < "SMYTHE" B$ < "9/12/78 QBASIC Functions and Statements Keywords Specific words which are not applicable to use as a variable on computer program are Keywords. These are also called reserved words. For example INPUT, GOTO, PRINT etc. Syntax A set of rules and regulation that must be followed to construct the program structure is called Syntax. It is one type of grammar to use the command and statement of computer. Statements A collection of commands used in the lines of a program is called statements. When the program is executed, the statements inside are executed one after another in a controlled sequence. Like all programming language, QBASIC also has its own grammar and vocabulary. They are used to check the syntax of commands and statements in a program when it is executed. It gives message about the validity of commands and statements based on this. According to the programming tasks, statement can be generally grouped into four categories. 1. Assignment Statement 2. Declaration Statement 3. Input / Output Statement 4. Control Statement 1. Assignment Statement: A statement used to assign value of a variable is called Assignment Statement. e.g., LET A = 25 B = 17 LET C = A* B LET Y = C In the examples above, the value of expression right of the equal to sign (=), is stored in the variable. This is quite different from what we learnt in the algebra, where A = B also implies that B = A. But here, A = B means that the value B is stored in the variable A. The word LET is optional in the assignment statement. e.g., LET A = B + C can be written as A = B + C. 2. Declaration Statement A statement used to define or declare a constant, variable or array etc. is called Declaration Statement. e.g., CONST PI = 3.141593 DIM A(4,4) REM This program gives the sum of integers SWAP a%, b% In the examples above: PI as a constant, A as an array of 4x4 dimension, REM as a remark is declared. This program gives the sum of integer and a statement for exchanging the values of the integer variables a and b, are also declared. 3. Input / Output Statement A statement to get data or display processed data in the screen or write it to a printer or a file is called Input / Output Statement. e.g., INPUT A INPUT "What is your Name ?"; Name$ PRINT "How are you ? "; Name$ PRINT TAB(25); "WEL – COME" WRITE #1, Name$, Age$ In the examples above, statements are declared to receive date in the variable A. "What is your Name?" is displayed on the screen and it waits to enter the name in the variable Name$. "How are you? " is displayed along with the data that you entered for Name$. The WEL-COME is displayed at the 25th column on the screen and the variable data Name$ and Age$ are written in the #1 file. 4. Control Statement A statement, which controls the program flow, while executing the program instructions one after another, is called Control Statement. e.g., a. GOTO lab10: b. IF Mark >= 80 THEN GOTO lab5:
c. IF I% = 15 THEN END
d. END
In the examples above, statements to control program flow are given.
Branch to a line with label lab10.
If Mark is greater or equal to 80 then branch to line with label lab5 and carryout the instruction of that line.
To stop the program flow if the value of the integer variable I is equal to 15.
End of the program.
Loop
Loop is a statement which executes one or more lines of code in certain number of times. The loop ends with the false condition. Every loop statement requires the following terms:
− Counter: It is a variable which controls the loop statement and provides the track to run the loop statement in certain number of times.
− Initial Value: The string value of loop statement is known as initial value.
− Sentient Value: This is the final value of loop statement.
− Step value: It is used to modify the value of counter by certain amount.
If...GOTO LOOP
This program uses IF----GOTO to create a loop.
x= 10
start:
Print x
x= x+1
If x < 15 Then GOTO start Output 10 11 12 13 14 For.....NEXT It is the count controlled loop which knows how many times the loop is to be executed. The loop is executed with the loop control variable at initial value to final value and values in between. Syntax: FOR = TO [STEP ]
[do this]
...
[and do this]
NEXT variable name
may be + or - and is optional. If omitted the default is +1. The code contained within the FOR loop will always be executed at least once because it is only at the 'NEXT' statement that the value of the variable is checked against the end value.
When the NEXT statement executes, the variable is modified by STEP value and compared against the end value. If the variable has not yet exceeded the end value, control is returned to the line following the FOR.
We can exit a FOR loop early with the EXIT FOR command.
WHILE....WEND
It is a loop statement that executes a series of statements in a loop as long as the given statement is true.
syntax:
WHILE
[do this]
..
[and this]
WEND
If the condition is true, the code following the WHILE is executed. When the WEND command is executed, it returns control to the WHILE statement (where the condition is tested again). When the condition evaluates to FALSE, control is passed to the statement following the WEND.
Do While.. Loop Construct
The DO WHILE…LOOP construct can be used when you don’t know how may times the loop should be executed before entering the loop
The WHILE statement checks to see if the condition is True, if it is then the loop continues to execute
The statements between the DO WHILE and LOOP are executed repeatedly until the condition is FALSE
Syntax:
DO
[this]
..
[and this]
LOOP WHILE / LOOP UNTIL
Or the structure may be:
DO WHILE Condition
statements to be repetitively executed….
LOOP
The while loop only terminates when the condition is False
If the condition is initially False, the loop may not execute at all !
The DO WHILE...LOOP will only execute the statements within it, if the condition is initially true. You may wish to have a loop construct that executes it’s statements at least once before exiting the loop
The DO..LOOP WHILE does it’s test at the end of the loop and so will execute it’s statements at least once
Example:
DO
PRINT "Enter a number."
PRINT "When you want to quit, press 0."
INPUT n r = n / 2 PRINT n; "/2 ="; r
LOOP WHILE n > 0
END
The Branching Statement
− The branching statement is decision making statement, depending upon the decision it can change the order of execution.
IF......THEN Statement
It helps the computer to check whether the relation is TRUE or FALSE.
Syntax:
IF [conditional] THEN
[do this]
[and do this]
...
[and also do this]
END IF
If the condition is true then block of code will be executed otherwise statement following END IF statement will be executed.
IF....THEN....ELSE
It is a decision making statement as it decides the path of the program. To choose between two different code blocks, the ELSE statement is used.
Syntax:
IF [conditional] THEN
[do this]
..
[and do this]
ELSE
[do that]
..
[and also that]
END IF
IF_ _ _ _ _ ELSEIF Statement
Syntax:
IF ( Condition ) THEN
Statement-1
ELSEIF (Condition) THEN
Statement-2
ELSEIF (Conditon) THEN
Statement-3
ELSE
Statement-4
ENDIF
SELECT-CASE Statement
Syntax:
SELECT CASE ( expression )
Statement-1
Case ( expression )
Statement-2
Case ( expression )
Statement-3
Case ELSE
Statement-4
END SELECT
CLS
PRINT "WELCOME"
PRINT "I HAVE AN ANSWER FOR ANY OF YOUR QUESTIONS"
input "WRITE YOUR QUESTION AND I'LL GIVE YOU AN ANSWER ", question$
10 RANDOMIZE TIMER
PRINT
answer=INT(RND*10+1)
SELECT CASE answer
CASE 1
PRINT "PLEASE REPHRASE YOUR QUESTION."
CASE 2
PRINT "YOUR QUESTION IS MEANINGLESS."
CASE 3
PRINT "DO YOU THINK I CAN ANSWER THIS?"
CASE 4
PRINT "THIS QUESTION LOOKS FUNNY."
END SELECT
PRINT "ENTER ANOTHER QUESTION", K$
GOTO 10
Function:
A function is a built-in formula to accomplish certain task such as mathematical, statistical, financial, logical/data calculations, etc. Functions in QBASIC are readymade programs which take some data, manipulate them and return the value, which may be string or numeric type. Programming languages also have certain functions like spread sheets or database software.
Every function has its unique name which once written and debugged, it can be used again and again. It may be used in any program which is called calling function.
TYPES OF FUNCTIONS:-
QBASIC supports two types of functions. They are:-
A) USER DEFINED FUNCTIONS:-
A function which is written and stored by the programmer to perform a specific task is known as User Defined Functions. When QBASIC does not provide a built in function to solve any particular problem required by the programmer in that case only programmers define this type of function. FUNCTION……………END FUNCTION statement can be used to define the function.
B) BUILD-IN OR LIBRARY FUNCTIONS:-
The functions which are provided by the QBASIC system and also allow the programmer to use them according to the requirement are known as BUILT-IN or Library Functions. These functions are required to be called by the programmer to use them in a program. Some common Build-IN or Library Functions are LEN, LEFT$, RIGHT$, MID$, UCASE$, LCASE$, CHR$……..etc.
TYPES OF BUILD-IN OR LIBRARY FUNCTIONS:-
A) STRING FUNCTIONS:-
String represents alphanumeric characters that are enclosed within quotation marks. QBASIC has many string functions that can only be applied to string, to modify and alter them if necessary. These are called string manipulators, since they manipulate rearrange the values within a string. Some of the string functions are as follows:-
LEFT$:-
It is a processing function that extracts the specific number of characters beginning from the leftmost character of the string.
LEFT$(String expression, n)
For e.g.:-
CLS
A$=”BIRATNAGAR”
FORI = 1 TO 10
PRINT LEFT$(A$, I)
NEXT I
END
RIGHT$:-
It is a processing function that extracts the specific number of characters beginning from rightmost character of the string. It means that it counts from right but write from left to right position.
RIGHT$(string expression, n)
For e.g.:-
CLS
A$=”PRINCE”
FOR I= 1 TO 6
PRINT RIGHT$(A$, I)
NEXT I
END
MID$:-
It is a processing function that allows replacing a portion of one string with another string or it returns to specific number of characters from a string.
MID$(String expression, start, length)
For e.g.:-
CLS
A$=”KATHMANDU”
PRINT MID$(A$, 5, 3)
END
LEN :-
It is a string processing function which returns the number of characters in a string or the number of bytes required by a variable.
LEN (String expression) or LEN (Variable)
For e.g.:- CLS
A$=”PRINCE”
PRINT LEN (A$)
END
LCASE$:-
It is a processing function which converts the string into lower case.
LCASE$(String expression)
For e.g.:-
CLS
A$=”PRINCE”
PRINT LCASE$(A$)
END
UCASE$:-
It is a processing function which converts the string into upper case.
UCASE$(String expression)
For e.g.:-
CLS
A$=”prince”
PRINT UCASE$(A$)
END
ASC :-
It is a processing function which is used to return a numeric value that is the ASCII code for the first character of the string. It is commonly used to intercept special characters entered from the keyboard.
ASC (String expression)
For e.g.:-
CLS
A$=”A”
PRINT ASC (A$)
END
CHR$:-
It is a processing function which is used to convert an ASCII code to the character it represents. It is commonly used to send a special character to the terminal.
CHR$(n)
For eg :-
CLS A=97
PRINT CHR$(A)
END
STR$ Function:-
It is a processing function to convert a numeric expression to its string represent.
STR$(n)
Where:-
n = any numerical expression
For e.g.:-
CLS
N=123
PRINT STR$(N)
END
VAL Function:-
It is a processing function which converts a string expression consisting of digits into value. The extracted value is numeric in nature and can be used for mathematical calculation. If the first character of a string is not numeric, then VAL will return 00(Zero)
VAL(N$)
For eg;-
CLS
N$=”123AB45”
P=VAL(N$)
PRINT ”Expected value”;P
END
LTRIM$ Function:-
It is a processing function which removes the leading blank space from the string expression.
LTRIM$(String expression)
For eg:-
CLS
A$=”PRINCE”
PRINT LTRIM$(A$)
END
RTRIM$ Function:-
It is a processing function which removes the trailing blank space of the string expression.
RTRIM$(String expression)
For eg:-
CLS
A$=”PRINCE”
PRINT RTRIM$(A$)
END
STRING$ Function:-
It is a processing which is used with a print statement to display a particular character and specified number of times.
STRING$(n ASCII code or character)
Where:
n represents the no. of times it should be printed (repeated)
ASCII code/char. represents the character code of any no. or
string of ASCII.
For eg:-
CLS
PRINT STRING$ (10,65)
CLS
PRINT STRING$ (10,”P”)
INSTR function:-
It is a processing function that returns the position of the first occurrence of a string in another string. But if the searched string is not found then it returns 0(Zero).
INSTR(start%, expression 1, expression 2)
Where to search what to search
Where:-
Start% represents the seted position of character where the search starts. If it is not mentioned then search starts from the first position.
For eg:-
CLS
A$=”World of PRINCE
P$=”PRINCE”
S=INSTR (1,A$,P$)
PRINT “Word PRINCE begins at”;S
END
DATE$ Function:-
It is a processing function that can be used as a statement or a function. As a statement, DATE$ sets the com puter date. As a function,DATE$ returns the computer’s current date in DD/MMYYYY format.
Syntax
As a statement As a function
DATE$=String expression DATE$
For eg:
TIME$ Function:-
It is a processing functikon that can be used as a statement or a function.As a statement, TIME$ sets the computer’s clock to the specified time of day. As a function,TIME$ returns the computer’s current time according
to the computer’s clock(in hh:mm:ss format)
Syntax
As a statement As a function
TIME$=String expression TIME$
INKEY$ FUNCTION:-
The INKEY$ Function is used to read a character from the keyboard buffer. It reads only one character even if there are several characters waiting in the keyboard buffer.
Syntax
INKEY$
For eg:
CLS
TOP: A$=INKEY$
IF A$=” “ THEN
GOTO TOP:
PRINT A$;”was pressed by user”
END
INPUT$ Function:-
It is a string processing function which waits until the specified numbers of characters are pressed on keyboard or reacts disk file. Users do not have to press ‘ENTER’ key after the last character is typed or pressed.
Syntax
VAR$=INPUT$(n) [, #file number]
For eg;-
P$=INPUT$(2, #1)
Which reads 2 character from an opened file whose file number is”1”.
NOTE: You can use the function without specifying # and file number if it is not needed.
For e.g.:-
CLS
INPUT “Enter your name is 5 digits”; N$
N$=INPUT$(5)
PRINT N$
END
B) MATHMATICAL FUNCTIONS:-
Mathematical represents numeric characters (data/value)which are used to process numeric data and solve problems. Numeric functions are referenced by a symbolic name. When the are called, they return a single value that can be either an integer or a single precision data type.
Some mathematical functions are as follows:
i) ABS Function:-
It is a math function that returns the absolute value of a numeric expression. A number’s absolute is its value without a “+” or”-“sign.(it also returns –ve number into +ve number)
Syntax
ABS(numeric expression)
For eg:-
PRINT ABS (23.456)
PRINT ABS (-9.76)
PRINT ABS (2.99)
ii) COS Function:-
It is a math function which computes the cosine of an angle. It can be any number or expression. To convert degrees to radians use the formula:
Radian = degree*(Pi/180)
where,
Pi=3.14
Syntax
COS(numeric expression)
For eg;-
CLS
INPUT “Enter an angle in degree”; a
R=a*3.14/180
P=cos(r)
PRINT “Cosine of”;a;”degree”;”is”;p
END
iii) INT function:-
It is a math function that returns the largest integer less than or equal to a numeric expression or it is used to round the number to their integer value. (Usually round numbers to down)
Syntax
INT(numeric expression)
For e.g.:-
CLS
PRINT INT(-23.409)
PRINT INT(50.56)
LET P=INT(SQR(21.6))
IF INT(P)>=0 THEN PRINT “Integer”
END
iv) CINT( ) Function:-
It is a math function used to convert numeric expression to an integer by rounding the fractional portion or it returns the integer to the given number.
Syntax
CINT (numeric expression)
For e.g.-
PRINT CINT (27.95)
PRINT CINT (20.29)
v) SIN FUNCTION:-
It is math function that returns the sine of an angle given in radians
Syntax
SIN (numeric expression)
For e.g.:-LET PI = 3.14
PRINT SIN(3*PI/2)
v) TAN Function:-
It is a math function that returns the tangent of an angle expressed in radians.
Syntax
TAN (numeric expression)
For e.g.:- For e.g.:-LET PI = 3.14
PRINT TAN(PI/2)
vi) SGN Function:-
It is a math function that indicates the sign of a numeric expression.
Syntax
SGN (numeric expression)
For e.g.:-
PRINT SGN(-3.78)
PRINT SGN(27.57)
PRINT SGN(0)
vii) SQR Function:-
It is a math function that returns the square root of positive number expression
Syntax
SQR (+ve numeric expression)
For e.g.-
CLS
INPUT “Length of side A”;A
INPUT “Length of side B”;B
C=SQR(A^2 + B^2)
PRINT”The hypotenuse is=”;C
END
ARRAY
An array is an ordered group of related items having a common variable name, all of the same data type. An individual data item within an array is called an Element. In another words, an array is a data structure that stores multiple values of similar type with a common name but having different subscript. An array consist of f a group of consecutive storage locations, each location containing a single element. An array is defined by using DIM statement. There are two types of array:
Single Dimensional Array: An array having series of similar type of data represented by a variable with a single subscript or index value known as single dimensional array. Example:
Dim sNames(2) As String will create an array that has 3 elements
sName(0)
sName(1)
sName(2)
Be careful! By default QBasic sets the lowest array element as 0, so in our case this means we have three elements. Arrays have a lower address or lower bound, and an upper address or upper bound.
We can alter the default lower bound by using Option Base
Option Base can be set to either 0 or 1
Option Base 0 ‘sets the lower bound to 0
Option Base 1 ‘sets the lower bound to 1
Examples:
1. DIM Scores(1 TO 40)
2. DIM Scores(21 TO 60)
3. DIM Name$(1 TO 50)
Storing Data in an Array
E.g.,
DIM Quiz(1 TO 5)
FOR Count = 1 TO 5
INPUT “Enter Quiz score: ”, Quiz(Count)
NEXT Count
Multidimensional Array: An array having series of similar type of data represented by a variable with double subscripts is known as multidimensional array.
Syntax: DIM [ array name] (index1, index2,....,indexn)
Example:DIM a (5,5)
Modular Programming In QBASIC
Modular Programming
The process of breaking a large program into small manageable tasks and designed them independently is called modular programming. A module program consists of a main module and one or more sub modules or procedures. Each sub module has a unique name. Modular Programming is a approach in which the program is divided into separate independent units is called modules.
A modular program consist of main module and sub-module.
1. Main module : Modular Programming structure consists of many modules,the program entry point is a module,which is located at the top of the order modules.This top level module is called main module. The main module is the controlling section of a modular programming.
2. Sub- module : Sub- module is a program which is written under the main module. A modular program may have one or more than one sub- module. It is called sub- program. Qbasic is also known as modular programming language because it allows the user to divide program into manageable and functional modules or blocks with the help of sub procedure and function procedure.
Merits of Modular Programming
• It reduces the program code.
• It is possible to use single module in different places.
• It makes debugging easier.
• It makes the maintenance of the program easier.
• It reduces the chance of changing the value of variable accidentally.
Procedures In Basic
There are two types of procedures in BASIC. They are as follows:
Sub Procedure : A sub procedure is a small manageable and functional part of a program that performs specific tasks and does not return any value to the calling module. A sub program is written with SUB....END SUB statements.
Some important features of sub procedure are as follows:
• It does not return any value.
• Sub procedure name can't be used as variable.
• Arguments can be passed to the sun program by reference or value.
Function Procedure : A function procedure is small manageable and functional part of a program that performs the specific tasks and returns a single value to the main program or calling module. A function is written withFUNCTION....... END FUNCTION statement.
Some important features of function procedure are as follows:
• It returns a value.
• Function procedure name has type declaration sign.
• Arguments can be passed to the sub-program by reference or by value.
Arguments
The constant or variables enclosed in the parentheses of procedure call statement and that are supplied to the procedure are known as arguments.The argument can be passed to a procedure either by reference or by value method.
Formal and Actual Parameter: Formal parameters are used to specify or declare the type of data to be passed to the procedures either by sub or function procedure.
Parameters
Variables in sub procedure declaration which accept data or variables passed to them from the calling module are known as parameters. It is also known as formal parameter.
Local and Global variable : A variable which is defined in a module ans is not accessible to any other modules is known as local variable. A variable in main module which can be accessed from any module or procedure of a program is known as global variable.
File Handling in QBASIC
After completing this lesson, student must be able to:
• Know about file handling.
• Explain some useful commands with their function and syntax.
• Discuss types of mode in sequential data file.
File Handling
Introduction
File Handling is a process to create data file, write data to the data file and read data from it. This note provides an information about file handling in QBASIC. Data are used in all the programs for retrieving information. In QBASIC you can store data in a separate file called a data file. Hence there are two types of files in data processing. They are:
• Program file :A program file contains a set of instructions that are needed for data processing. A program file has BAS extention.
• Date file : A data file contains only data that are required during data processing. In a data file related of a person or any thing are stored in a row known as a record.
File Handling
It is a process to create data file,write data to the data file and read data from it.
Types of File Handling
• Sequential Data File : It is a file that should be accessed in a sequential manner starting at the beginning of the data block and process ending in order until and end of data.
• Random Data File: It is a file which a key is used to point its appropriate record stored on a disk.
Some useful commands with their function and syntax
Files: This command is used to display all the files of current drive. Syntax: Files [File specification]
Shell: This command is used to go to DOS prompt temporarily.
NAME: This command is used to change the old file into new file. Syntax: Name " old file name" AS "New file name"
Kill: This command is used to remove the file from the disk. Syntax: Kill [ File Specification ]
MKDIR: This command is used to create a directory in a specific disk Syntax: MKDIR "path"
CHDIR: This command is used to change the directory. Syntax: CHDIR " path"
RMDIR: This command is used to remove the specific directory. Syntax: RMDIR "path"
System: This command is used to close the Q-BASIC program.
OPEN: This statement is used to open the file.
WRITE#: This statement is used to place the data into data file.
NPUT#: This statement is used to read each data and stores to corresponding variable.
LINE INPUT#: This statement reads entire line having maximum 255 characters and stores to a single string variable.
EOF ( ) : This statement is used to end a file. Syntax: EOF ( File number)
Modes of operations of sequential access data file
You need to open a sequential access data file in order to use it. A sequential data file can be opened in one of three modes.
Types of Mode:
• OUTPUT mode : A file is opened in output mode to write data to the file. When a file is opened in output mode BASIC always creates a new file. If a file with the name already exists then it will overwrite without warning.
• INPUT mode : A file is opened in input mode to read data from the file. The file must exist to open it in input mode otherwise error message "file not found" is displayed.
• APPEND mode : A file is opened in append mode to add data to an existing file. New data are added to the end of existing file. It is recommended mode for writing data to a file unless there is specific reason to create new.
Structured Programming - C Language
After completing this lesson, student must be able to:
• Explain difference between QBASIC and C-language.
• Structured programming - C language.
• Control structures in C.
C Language
C is a structured programming language developed by Dennis Ritchie at Bell Laboratories in 1972. Since C is a structured programming language, a program in C language can be divided into small logical and functional modules. C++ language is an expanded version of C.
Character set:
The character set consists of alphabet, digit or special symbols used to response information.
Character sets used in C
Alphabet Uppercase ( ie A, B..............Z)
Lowercase ( ie a, b ................z)
Digits 0, 1, 2 ................... 8, 9
Special symbols +, -, *, ( ) , etc.
Characteristics of C Language
• It is a small programming language that consumes less space.
• It has enough number of inbuilt functions and operators.
Keyword:
The character set consists of alphabet, digit or special symbols used to response information.
There are 32 characters in C:
Auto, If, While, For, Int, float. etc.
Data type:
Data type refers to the type of data or variable which is to be stored and used in the program.
List of data types
• Integer (int) = 2 bytes
• character (char) = 1 byte
• float (float) = 4 bytes
• double (long integer) = 8 bytes
Difference between QBASIC and C-Language
Q-BASIC C- Language
It is a high level language without feature of low level language. It is high level language with some features of low level language.
It is mostly used for designing application software. It is mostly used for designing system software.
Operators
Operators are the symbols which are used to compute values and test multiple operations. The data on which the operators are performed are known as operands.
Types of operator
• Arithmetic operator: The operators which perform mathematical expressions like addition, subtraction, multiplication and division.
• Relational operator: Relational operators are symbols used to compare two different expressions. The result of the comparison is either True or False.
• Logical operator: Logical operators performs tests on multiple relation. Example: A < B and A > B
• Unary operator: C also supports two very important operators called increment and decrement operators.
Loop
A loop causes a section of a program to be repeated a certain number of times. The repetition continues while the condition set for it remains true. When the condition becomes false, the loop ends the control is passed to the statement following the loop.
Variable
Those value which changes during program execution is called variable.Example: A = 5 where A is a variable
Constant
Those values which can't change during the program execution is called constant. Example: A = 10 where 10 is a constant
Rule for naming variables in C
• Space is not allowed in variable name.
• Both upper and lower case letters are permitted.
Printf: This statement is used to display the message on the screen.
Scarf: This statement is used to accept a value.
QBASIC Programming
QBASIC is the most popular high level programming language. Various versions of BASIC have been developed by Microsoft Company. This language is quite simple to understand and has been adopted by most of the microcomputers. It is suitable for both mathematical and business problems. It is compatible with MSDOS environment and it has two basic files QBASIC.EXE and QBASIC.HLP. We can edit, debug and execute the program using these two files.
The advantages of QBASIC
1. QBASIC is easy to learn and fun to practice. It may be called a "People's language".
2. It is available almost in every computer from micro to mainframe. Therefore, a program developed in a micro can run on bigger system with minor modifications.
3. It is suitable for mathematical and business application.
4. Program development cycle is quick, debugging is simple, and
5. Modification of program is quite easy.
Starting QBASIC
It occupies very low memory so it may be possible to run the system using floppy disk also. It is compatible with MS-DOS and have only two files QBASIC.EXE and QBASIC.HLP.
Steps
1. Get MS-DOS System and MS-DOS Prompt
C:\>
2. Change the Directory
C:\>CD QBASIC
C:\QBASIC>
3. Type QBASIC and press Enter
C:\QBASIC>QBASIC enter
When you are working with Windows system. Open QBASIC Folder on Windows.
Double click over the QBASIC.EXE icon. We will get the QBASIC System as below. Press ESC key and get the programming window of the QBASIC and type the program on the working of QBASIC.
Structure of Basic
To construct the QBASIC program we have to arrange some standard elements.
The elements are:
1. Character set
2. Variables and constant
3. Arithmetic expressions
4. Relational or Logical expressions
5. Keywords
6. Syntax
7. Library functions
The Character Set
QBASIC has the character set consisting of the following elements:
1. Alphabets: A, B, C,....Z
2. Digits: 0, 1, 2........,9 and
3. Special characters: + - * / ( ) . , $ ; ,: ,= ,> ,< , ^ The symbol ^ (caret) is used to denote exponentiation operator, the symbol * (asterisk) is used to denote multiplication and other symbols; have their usual meanings. Constants and Variables A quantity in a computer program which does not change its value during the execution of the program is called a constant and the quantity which may change its values during the execution of the program is called variable. QBASIC allows the following constants: • Numeric constant Numeric constant is one that is formed by a sequence of digits 0, 1, 2,.....9 and may include a decimal point. A numeric constant known as number may be integer or a real number. 383, +57, 0, -6.2 and 6.15E4 are valid numeric constants. The number 6.15E4, in fact represent 6.15 * 104. The notation E is used to represent exponential form. The number after E is the exponent which can be positive or negative. However, its length cannot exceed two digits. It is also important to keep in mind that o QBASIC does not distinguish between an integer and fraction. o Commands are not allowed in a numeric constant. o The limit on the number of digits that can be used varies from computer to computer. Normally, a numeric constant can have up to a maximum of eight digits. • String constant A string constant consists of a sequence of characters which must be enclosed by a quotation mark. Simply defined, variable is a name, which can contain a value. Programming involves giving values to these names and presenting them in some form to the user. A variable has a type, which is defined by the kind of value it holds. In QBASIC, variables are also of two types: 1. Numeric variable :Numeric variable can assume numeric value and is represented by an alphabet or an alphabet followed by another alphabet or digit. For example A, C, A2, ABC, A6 etc, represent numeric variables. 2. String variable : A string variable is represented by an alphabet followed by dollar ($) sign. It should be kept in mind that while constructing the string variable, dollar ($) should be the last character. For example B1$, NAME$, BOOK1$, etc are valid string variables. There are two methods of telling the computer what kind of variable you are using: One-way is to just use the variable. This is called implicit declaration. Another way is to declare the variable AS a type, which can be done by using the DIM statement. E.g. a variable called number, which would contain an integer (whole number, no digits after the decimal point) is defined as: DIM number AS INTEGER Then you would use that variable as an integer. The word DIM actually originates from the word Dimension, it will be clear when we discuss arrays. This is called explicit declaration. We can put a symbol after the variable name, which is defined as representing that type. QBasic has a set of symbols, which represent each variable type: $ String % Integer & Long ! Single # Double Appending one of these symbols to the name of a variable when you use it in the program tells the computer that you are using it as that type. If we don't define the type of the variable, then QBasic assumes it is of the Single Precision type, which can often yield unexpected results. Type of variable Number / Characters Memory Example String 0 to 32767 character 1 Byte of each character A$ Integer A whole number – 32767 to 32767 2 Bytes A% Long Integer A whole number- 2 and more than 2 billion 4 Bytes A& Single precision A number with up to 7 digits after decimal point 4 Bytes A! Double precision A number with up to 15 digits after decimal point 8 Bytes A# The DIM statement is used to declare variables as follows: DIM state AS STRING DIM number AS INTEGER DIM profit AS DOUBLE DIM gpa AS SINGLE Some valid an invalid numeric variable names are provided below: Valid Numeric Variable Names firstTest profit& gpa! total.Price company8 COURSE2D Invalid Numeric Variable Names 1stClass --> (must begin with letter)
total Price --> (no spaces)
name,First --> (no commas)
Arithmetic, Relational or Logical Expression
Various symbols used to perform arithmetic and logical operations in programming language.
E.g., 18 + 56, in this + is the operator and 18 and 56 are operand.
Eg., A – B < C, in this – and < are the operators and A, B and C are operand. In any programming language value of arithmetic or logical operations are tested by using various operator symbols. Operators can be classified in 4 types. Arithmetic Operators Relational Operators Logical Operators and String Operators Arithmetic Expressions QBASIC can handle arithmetic expression involving the following arithmetic operators: Operator Meaning Example + Addition A + B OR 10 + 5 =15 - Subtraction C – D OR 30 – 23 =7 * Multiplication P * Q or 12 * 5 = 60 / Division R / S OR 7 / 2 = 3.5 \ Integer Division R\S OR 7\ 2 = 3 MOD Modulus Division 5 MOD 2 = 1 ^ To the power X^2 or 6^2 = 36 In addition to this hierarchy of operations, the following rules must be kept in mind in arithmetic expression: • Two operations must not appear together. For example, C+-D, A/-C, etc are not permitted. • String constants and string variables should not be used in arithmetic expressions. For example P+P$ is wrong. • When brackets are used, they must be used in pairs, i.e. every left bracket must be matched with a right bracket. • Denominator of an expression should not be zero. • Within a given pair of parentheses, the natural hierarchy of operations will apply. Relational or Logical Expressions Relational Operator Meaning = Equal to > Greater than
< Less than <= Less than or equal to >= Greater than or equal to
<> Not equal to
A relational expression is formed by using any of the following relational operators. Relational operators are used to compare two or more values. Using this we can compare value/s of variable/s with a constant. In QBASIC the following relational operators can be used.
When expressions are used on either side of relational operators, the expressions will be evaluated first and then the results of expressions compared. This means that relational operators come last in hierarchy of operators.
Logical operators
QBASIC, also supports logical operators to perform logical operation on numerical values. Logical operators are used to connect two or more relations and return a TRUE or FALSE value to be used in a decision.
The common logical operators are:
• AND Conjunction
• OR Disjunction
• NOT Logical Negation
For example, the expression A>50 AND B>150 is TRUE when A is more than 50 and at the same time B is more than 150.
Logical operators return results as indicated in the following tables. T indicates a TRUE and F indicates FALSE. X and Y are relational expressions.
AND Operator OR Operator
X Y X AND Y
T T T
T F F
F T F
F F T
X Y X OR Y
T T T
T F T
F T T
F F F
X NOT X
T F
F T
NOT Operator
String Operator:
A string expression consists of string constants, string variables and other string expressions combined by string operators.
There are two classes of string operations: concatenation and string function. The act of concatenating two strings is called concatenation. The plus (+) symbol is the concatenation operator for strings.
For example, the following program fragment combines the string variables A$ and B$ to produce the value FILENAME:
A$ = "FILE": B$ = "NAME"
PRINT A$ + B$
PRINT "NEW " + A$ + B$
Output:
FILENAME
NEW FILENAME
All string constants used in comparison expressions must be enclosed in quotation marks.
The following are examples of true string expressions:
"AA" < "AB" "FILENAME" = "FILE"+"NAME" "X&" > "X#"
"CL " > "CL"
"kg" > "KG"
"SMYTH" < "SMYTHE" B$ < "9/12/78 QBASIC Functions and Statements Keywords Specific words which are not applicable to use as a variable on computer program are Keywords. These are also called reserved words. For example INPUT, GOTO, PRINT etc. Syntax A set of rules and regulation that must be followed to construct the program structure is called Syntax. It is one type of grammar to use the command and statement of computer. Statements A collection of commands used in the lines of a program is called statements. When the program is executed, the statements inside are executed one after another in a controlled sequence. Like all programming language, QBASIC also has its own grammar and vocabulary. They are used to check the syntax of commands and statements in a program when it is executed. It gives message about the validity of commands and statements based on this. According to the programming tasks, statement can be generally grouped into four categories. 1. Assignment Statement 2. Declaration Statement 3. Input / Output Statement 4. Control Statement 1. Assignment Statement: A statement used to assign value of a variable is called Assignment Statement. e.g., LET A = 25 B = 17 LET C = A* B LET Y = C In the examples above, the value of expression right of the equal to sign (=), is stored in the variable. This is quite different from what we learnt in the algebra, where A = B also implies that B = A. But here, A = B means that the value B is stored in the variable A. The word LET is optional in the assignment statement. e.g., LET A = B + C can be written as A = B + C. 2. Declaration Statement A statement used to define or declare a constant, variable or array etc. is called Declaration Statement. e.g., CONST PI = 3.141593 DIM A(4,4) REM This program gives the sum of integers SWAP a%, b% In the examples above: PI as a constant, A as an array of 4x4 dimension, REM as a remark is declared. This program gives the sum of integer and a statement for exchanging the values of the integer variables a and b, are also declared. 3. Input / Output Statement A statement to get data or display processed data in the screen or write it to a printer or a file is called Input / Output Statement. e.g., INPUT A INPUT "What is your Name ?"; Name$ PRINT "How are you ? "; Name$ PRINT TAB(25); "WEL – COME" WRITE #1, Name$, Age$ In the examples above, statements are declared to receive date in the variable A. "What is your Name?" is displayed on the screen and it waits to enter the name in the variable Name$. "How are you? " is displayed along with the data that you entered for Name$. The WEL-COME is displayed at the 25th column on the screen and the variable data Name$ and Age$ are written in the #1 file. 4. Control Statement A statement, which controls the program flow, while executing the program instructions one after another, is called Control Statement. e.g., a. GOTO lab10: b. IF Mark >= 80 THEN GOTO lab5:
c. IF I% = 15 THEN END
d. END
In the examples above, statements to control program flow are given.
Branch to a line with label lab10.
If Mark is greater or equal to 80 then branch to line with label lab5 and carryout the instruction of that line.
To stop the program flow if the value of the integer variable I is equal to 15.
End of the program.
Loop
Loop is a statement which executes one or more lines of code in certain number of times. The loop ends with the false condition. Every loop statement requires the following terms:
− Counter: It is a variable which controls the loop statement and provides the track to run the loop statement in certain number of times.
− Initial Value: The string value of loop statement is known as initial value.
− Sentient Value: This is the final value of loop statement.
− Step value: It is used to modify the value of counter by certain amount.
If...GOTO LOOP
This program uses IF----GOTO to create a loop.
x= 10
start:
Print x
x= x+1
If x < 15 Then GOTO start Output 10 11 12 13 14 For.....NEXT It is the count controlled loop which knows how many times the loop is to be executed. The loop is executed with the loop control variable at initial value to final value and values in between. Syntax: FOR
[do this]
...
[and do this]
NEXT variable name
When the NEXT statement executes, the variable is modified by STEP value and compared against the end value. If the variable has not yet exceeded the end value, control is returned to the line following the FOR.
We can exit a FOR loop early with the EXIT FOR command.
WHILE....WEND
It is a loop statement that executes a series of statements in a loop as long as the given statement is true.
syntax:
WHILE
[do this]
..
[and this]
WEND
If the condition is true, the code following the WHILE is executed. When the WEND command is executed, it returns control to the WHILE statement (where the condition is tested again). When the condition evaluates to FALSE, control is passed to the statement following the WEND.
Do While.. Loop Construct
The DO WHILE…LOOP construct can be used when you don’t know how may times the loop should be executed before entering the loop
The WHILE statement checks to see if the condition is True, if it is then the loop continues to execute
The statements between the DO WHILE and LOOP are executed repeatedly until the condition is FALSE
Syntax:
DO
[this]
..
[and this]
LOOP WHILE
Or the structure may be:
DO WHILE Condition
statements to be repetitively executed….
LOOP
The while loop only terminates when the condition is False
If the condition is initially False, the loop may not execute at all !
The DO WHILE...LOOP will only execute the statements within it, if the condition is initially true. You may wish to have a loop construct that executes it’s statements at least once before exiting the loop
The DO..LOOP WHILE does it’s test at the end of the loop and so will execute it’s statements at least once
Example:
DO
PRINT "Enter a number."
PRINT "When you want to quit, press 0."
INPUT n r = n / 2 PRINT n; "/2 ="; r
LOOP WHILE n > 0
END
The Branching Statement
− The branching statement is decision making statement, depending upon the decision it can change the order of execution.
IF......THEN Statement
It helps the computer to check whether the relation is TRUE or FALSE.
Syntax:
IF [conditional] THEN
[do this]
[and do this]
...
[and also do this]
END IF
If the condition is true then block of code will be executed otherwise statement following END IF statement will be executed.
IF....THEN....ELSE
It is a decision making statement as it decides the path of the program. To choose between two different code blocks, the ELSE statement is used.
Syntax:
IF [conditional] THEN
[do this]
..
[and do this]
ELSE
[do that]
..
[and also that]
END IF
IF_ _ _ _ _ ELSEIF Statement
Syntax:
IF ( Condition ) THEN
Statement-1
ELSEIF (Condition) THEN
Statement-2
ELSEIF (Conditon) THEN
Statement-3
ELSE
Statement-4
ENDIF
SELECT-CASE Statement
Syntax:
SELECT CASE ( expression )
Statement-1
Case ( expression )
Statement-2
Case ( expression )
Statement-3
Case ELSE
Statement-4
END SELECT
CLS
PRINT "WELCOME"
PRINT "I HAVE AN ANSWER FOR ANY OF YOUR QUESTIONS"
input "WRITE YOUR QUESTION AND I'LL GIVE YOU AN ANSWER ", question$
10 RANDOMIZE TIMER
answer=INT(RND*10+1)
SELECT CASE answer
CASE 1
PRINT "PLEASE REPHRASE YOUR QUESTION."
CASE 2
PRINT "YOUR QUESTION IS MEANINGLESS."
CASE 3
PRINT "DO YOU THINK I CAN ANSWER THIS?"
CASE 4
PRINT "THIS QUESTION LOOKS FUNNY."
END SELECT
PRINT "ENTER ANOTHER QUESTION", K$
GOTO 10
Function:
A function is a built-in formula to accomplish certain task such as mathematical, statistical, financial, logical/data calculations, etc. Functions in QBASIC are readymade programs which take some data, manipulate them and return the value, which may be string or numeric type. Programming languages also have certain functions like spread sheets or database software.
Every function has its unique name which once written and debugged, it can be used again and again. It may be used in any program which is called calling function.
TYPES OF FUNCTIONS:-
QBASIC supports two types of functions. They are:-
A) USER DEFINED FUNCTIONS:-
A function which is written and stored by the programmer to perform a specific task is known as User Defined Functions. When QBASIC does not provide a built in function to solve any particular problem required by the programmer in that case only programmers define this type of function. FUNCTION……………END FUNCTION statement can be used to define the function.
B) BUILD-IN OR LIBRARY FUNCTIONS:-
The functions which are provided by the QBASIC system and also allow the programmer to use them according to the requirement are known as BUILT-IN or Library Functions. These functions are required to be called by the programmer to use them in a program. Some common Build-IN or Library Functions are LEN, LEFT$, RIGHT$, MID$, UCASE$, LCASE$, CHR$……..etc.
TYPES OF BUILD-IN OR LIBRARY FUNCTIONS:-
A) STRING FUNCTIONS:-
String represents alphanumeric characters that are enclosed within quotation marks. QBASIC has many string functions that can only be applied to string, to modify and alter them if necessary. These are called string manipulators, since they manipulate rearrange the values within a string. Some of the string functions are as follows:-
LEFT$:-
It is a processing function that extracts the specific number of characters beginning from the leftmost character of the string.
LEFT$(String expression, n)
For e.g.:-
CLS
A$=”BIRATNAGAR”
FORI = 1 TO 10
PRINT LEFT$(A$, I)
NEXT I
END
RIGHT$:-
It is a processing function that extracts the specific number of characters beginning from rightmost character of the string. It means that it counts from right but write from left to right position.
RIGHT$(string expression, n)
For e.g.:-
CLS
A$=”PRINCE”
FOR I= 1 TO 6
PRINT RIGHT$(A$, I)
NEXT I
END
MID$:-
It is a processing function that allows replacing a portion of one string with another string or it returns to specific number of characters from a string.
MID$(String expression, start, length)
For e.g.:-
CLS
A$=”KATHMANDU”
PRINT MID$(A$, 5, 3)
END
LEN :-
It is a string processing function which returns the number of characters in a string or the number of bytes required by a variable.
LEN (String expression) or LEN (Variable)
For e.g.:- CLS
A$=”PRINCE”
PRINT LEN (A$)
END
LCASE$:-
It is a processing function which converts the string into lower case.
LCASE$(String expression)
For e.g.:-
CLS
A$=”PRINCE”
PRINT LCASE$(A$)
END
UCASE$:-
It is a processing function which converts the string into upper case.
UCASE$(String expression)
For e.g.:-
CLS
A$=”prince”
PRINT UCASE$(A$)
END
ASC :-
It is a processing function which is used to return a numeric value that is the ASCII code for the first character of the string. It is commonly used to intercept special characters entered from the keyboard.
ASC (String expression)
For e.g.:-
CLS
A$=”A”
PRINT ASC (A$)
END
CHR$:-
It is a processing function which is used to convert an ASCII code to the character it represents. It is commonly used to send a special character to the terminal.
CHR$(n)
For eg :-
CLS A=97
PRINT CHR$(A)
END
STR$ Function:-
It is a processing function to convert a numeric expression to its string represent.
STR$(n)
Where:-
n = any numerical expression
For e.g.:-
CLS
N=123
PRINT STR$(N)
END
VAL Function:-
It is a processing function which converts a string expression consisting of digits into value. The extracted value is numeric in nature and can be used for mathematical calculation. If the first character of a string is not numeric, then VAL will return 00(Zero)
VAL(N$)
For eg;-
CLS
N$=”123AB45”
P=VAL(N$)
PRINT ”Expected value”;P
END
LTRIM$ Function:-
It is a processing function which removes the leading blank space from the string expression.
LTRIM$(String expression)
For eg:-
CLS
A$=”PRINCE”
PRINT LTRIM$(A$)
END
RTRIM$ Function:-
It is a processing function which removes the trailing blank space of the string expression.
RTRIM$(String expression)
For eg:-
CLS
A$=”PRINCE”
PRINT RTRIM$(A$)
END
STRING$ Function:-
It is a processing which is used with a print statement to display a particular character and specified number of times.
STRING$(n ASCII code or character)
Where:
n represents the no. of times it should be printed (repeated)
ASCII code/char. represents the character code of any no. or
string of ASCII.
For eg:-
CLS
PRINT STRING$ (10,65)
CLS
PRINT STRING$ (10,”P”)
INSTR function:-
It is a processing function that returns the position of the first occurrence of a string in another string. But if the searched string is not found then it returns 0(Zero).
INSTR(start%, expression 1, expression 2)
Where to search what to search
Where:-
Start% represents the seted position of character where the search starts. If it is not mentioned then search starts from the first position.
For eg:-
CLS
A$=”World of PRINCE
P$=”PRINCE”
S=INSTR (1,A$,P$)
PRINT “Word PRINCE begins at”;S
END
DATE$ Function:-
It is a processing function that can be used as a statement or a function. As a statement, DATE$ sets the com puter date. As a function,DATE$ returns the computer’s current date in DD/MMYYYY format.
Syntax
As a statement As a function
DATE$=String expression DATE$
For eg:
TIME$ Function:-
It is a processing functikon that can be used as a statement or a function.As a statement, TIME$ sets the computer’s clock to the specified time of day. As a function,TIME$ returns the computer’s current time according
to the computer’s clock(in hh:mm:ss format)
Syntax
As a statement As a function
TIME$=String expression TIME$
INKEY$ FUNCTION:-
The INKEY$ Function is used to read a character from the keyboard buffer. It reads only one character even if there are several characters waiting in the keyboard buffer.
Syntax
INKEY$
For eg:
CLS
TOP: A$=INKEY$
IF A$=” “ THEN
GOTO TOP:
PRINT A$;”was pressed by user”
END
INPUT$ Function:-
It is a string processing function which waits until the specified numbers of characters are pressed on keyboard or reacts disk file. Users do not have to press ‘ENTER’ key after the last character is typed or pressed.
Syntax
VAR$=INPUT$(n) [, #file number]
For eg;-
P$=INPUT$(2, #1)
Which reads 2 character from an opened file whose file number is”1”.
NOTE: You can use the function without specifying # and file number if it is not needed.
For e.g.:-
CLS
INPUT “Enter your name is 5 digits”; N$
N$=INPUT$(5)
PRINT N$
END
B) MATHMATICAL FUNCTIONS:-
Mathematical represents numeric characters (data/value)which are used to process numeric data and solve problems. Numeric functions are referenced by a symbolic name. When the are called, they return a single value that can be either an integer or a single precision data type.
Some mathematical functions are as follows:
i) ABS Function:-
It is a math function that returns the absolute value of a numeric expression. A number’s absolute is its value without a “+” or”-“sign.(it also returns –ve number into +ve number)
Syntax
ABS(numeric expression)
For eg:-
PRINT ABS (23.456)
PRINT ABS (-9.76)
PRINT ABS (2.99)
ii) COS Function:-
It is a math function which computes the cosine of an angle. It can be any number or expression. To convert degrees to radians use the formula:
Radian = degree*(Pi/180)
where,
Pi=3.14
Syntax
COS(numeric expression)
For eg;-
CLS
INPUT “Enter an angle in degree”; a
R=a*3.14/180
P=cos(r)
PRINT “Cosine of”;a;”degree”;”is”;p
END
iii) INT function:-
It is a math function that returns the largest integer less than or equal to a numeric expression or it is used to round the number to their integer value. (Usually round numbers to down)
Syntax
INT(numeric expression)
For e.g.:-
CLS
PRINT INT(-23.409)
PRINT INT(50.56)
LET P=INT(SQR(21.6))
IF INT(P)>=0 THEN PRINT “Integer”
END
iv) CINT( ) Function:-
It is a math function used to convert numeric expression to an integer by rounding the fractional portion or it returns the integer to the given number.
Syntax
CINT (numeric expression)
For e.g.-
PRINT CINT (27.95)
PRINT CINT (20.29)
v) SIN FUNCTION:-
It is math function that returns the sine of an angle given in radians
Syntax
SIN (numeric expression)
For e.g.:-LET PI = 3.14
PRINT SIN(3*PI/2)
v) TAN Function:-
It is a math function that returns the tangent of an angle expressed in radians.
Syntax
TAN (numeric expression)
For e.g.:- For e.g.:-LET PI = 3.14
PRINT TAN(PI/2)
vi) SGN Function:-
It is a math function that indicates the sign of a numeric expression.
Syntax
SGN (numeric expression)
For e.g.:-
PRINT SGN(-3.78)
PRINT SGN(27.57)
PRINT SGN(0)
vii) SQR Function:-
It is a math function that returns the square root of positive number expression
Syntax
SQR (+ve numeric expression)
For e.g.-
CLS
INPUT “Length of side A”;A
INPUT “Length of side B”;B
C=SQR(A^2 + B^2)
PRINT”The hypotenuse is=”;C
END
ARRAY
An array is an ordered group of related items having a common variable name, all of the same data type. An individual data item within an array is called an Element. In another words, an array is a data structure that stores multiple values of similar type with a common name but having different subscript. An array consist of f a group of consecutive storage locations, each location containing a single element. An array is defined by using DIM statement. There are two types of array:
Single Dimensional Array: An array having series of similar type of data represented by a variable with a single subscript or index value known as single dimensional array. Example:
Dim sNames(2) As String will create an array that has 3 elements
sName(0)
sName(1)
sName(2)
Be careful! By default QBasic sets the lowest array element as 0, so in our case this means we have three elements. Arrays have a lower address or lower bound, and an upper address or upper bound.
We can alter the default lower bound by using Option Base
Option Base can be set to either 0 or 1
Option Base 0 ‘sets the lower bound to 0
Option Base 1 ‘sets the lower bound to 1
Examples:
1. DIM Scores(1 TO 40)
2. DIM Scores(21 TO 60)
3. DIM Name$(1 TO 50)
Storing Data in an Array
E.g.,
DIM Quiz(1 TO 5)
FOR Count = 1 TO 5
INPUT “Enter Quiz score: ”, Quiz(Count)
NEXT Count
Multidimensional Array: An array having series of similar type of data represented by a variable with double subscripts is known as multidimensional array.
Syntax: DIM [ array name] (index1, index2,....,indexn)
Example:DIM a (5,5)
Modular Programming In QBASIC
Modular Programming
The process of breaking a large program into small manageable tasks and designed them independently is called modular programming. A module program consists of a main module and one or more sub modules or procedures. Each sub module has a unique name. Modular Programming is a approach in which the program is divided into separate independent units is called modules.
A modular program consist of main module and sub-module.
1. Main module : Modular Programming structure consists of many modules,the program entry point is a module,which is located at the top of the order modules.This top level module is called main module. The main module is the controlling section of a modular programming.
2. Sub- module : Sub- module is a program which is written under the main module. A modular program may have one or more than one sub- module. It is called sub- program. Qbasic is also known as modular programming language because it allows the user to divide program into manageable and functional modules or blocks with the help of sub procedure and function procedure.
Merits of Modular Programming
• It reduces the program code.
• It is possible to use single module in different places.
• It makes debugging easier.
• It makes the maintenance of the program easier.
• It reduces the chance of changing the value of variable accidentally.
Procedures In Basic
There are two types of procedures in BASIC. They are as follows:
Sub Procedure : A sub procedure is a small manageable and functional part of a program that performs specific tasks and does not return any value to the calling module. A sub program is written with SUB....END SUB statements.
Some important features of sub procedure are as follows:
• It does not return any value.
• Sub procedure name can't be used as variable.
• Arguments can be passed to the sun program by reference or value.
Function Procedure : A function procedure is small manageable and functional part of a program that performs the specific tasks and returns a single value to the main program or calling module. A function is written withFUNCTION....... END FUNCTION statement.
Some important features of function procedure are as follows:
• It returns a value.
• Function procedure name has type declaration sign.
• Arguments can be passed to the sub-program by reference or by value.
Arguments
The constant or variables enclosed in the parentheses of procedure call statement and that are supplied to the procedure are known as arguments.The argument can be passed to a procedure either by reference or by value method.
Formal and Actual Parameter: Formal parameters are used to specify or declare the type of data to be passed to the procedures either by sub or function procedure.
Parameters
Variables in sub procedure declaration which accept data or variables passed to them from the calling module are known as parameters. It is also known as formal parameter.
Local and Global variable : A variable which is defined in a module ans is not accessible to any other modules is known as local variable. A variable in main module which can be accessed from any module or procedure of a program is known as global variable.
File Handling in QBASIC
After completing this lesson, student must be able to:
• Know about file handling.
• Explain some useful commands with their function and syntax.
• Discuss types of mode in sequential data file.
File Handling
Introduction
File Handling is a process to create data file, write data to the data file and read data from it. This note provides an information about file handling in QBASIC. Data are used in all the programs for retrieving information. In QBASIC you can store data in a separate file called a data file. Hence there are two types of files in data processing. They are:
• Program file :A program file contains a set of instructions that are needed for data processing. A program file has BAS extention.
• Date file : A data file contains only data that are required during data processing. In a data file related of a person or any thing are stored in a row known as a record.
File Handling
It is a process to create data file,write data to the data file and read data from it.
Types of File Handling
• Sequential Data File : It is a file that should be accessed in a sequential manner starting at the beginning of the data block and process ending in order until and end of data.
• Random Data File: It is a file which a key is used to point its appropriate record stored on a disk.
Some useful commands with their function and syntax
Files: This command is used to display all the files of current drive. Syntax: Files [File specification]
Shell: This command is used to go to DOS prompt temporarily.
NAME: This command is used to change the old file into new file. Syntax: Name " old file name" AS "New file name"
Kill: This command is used to remove the file from the disk. Syntax: Kill [ File Specification ]
MKDIR: This command is used to create a directory in a specific disk Syntax: MKDIR "path"
CHDIR: This command is used to change the directory. Syntax: CHDIR " path"
RMDIR: This command is used to remove the specific directory. Syntax: RMDIR "path"
System: This command is used to close the Q-BASIC program.
OPEN: This statement is used to open the file.
WRITE#: This statement is used to place the data into data file.
NPUT#: This statement is used to read each data and stores to corresponding variable.
LINE INPUT#: This statement reads entire line having maximum 255 characters and stores to a single string variable.
EOF ( ) : This statement is used to end a file. Syntax: EOF ( File number)
Modes of operations of sequential access data file
You need to open a sequential access data file in order to use it. A sequential data file can be opened in one of three modes.
Types of Mode:
• OUTPUT mode : A file is opened in output mode to write data to the file. When a file is opened in output mode BASIC always creates a new file. If a file with the name already exists then it will overwrite without warning.
• INPUT mode : A file is opened in input mode to read data from the file. The file must exist to open it in input mode otherwise error message "file not found" is displayed.
• APPEND mode : A file is opened in append mode to add data to an existing file. New data are added to the end of existing file. It is recommended mode for writing data to a file unless there is specific reason to create new.
Structured Programming - C Language
After completing this lesson, student must be able to:
• Explain difference between QBASIC and C-language.
• Structured programming - C language.
• Control structures in C.
C Language
C is a structured programming language developed by Dennis Ritchie at Bell Laboratories in 1972. Since C is a structured programming language, a program in C language can be divided into small logical and functional modules. C++ language is an expanded version of C.
Character set:
The character set consists of alphabet, digit or special symbols used to response information.
Character sets used in C
Alphabet Uppercase ( ie A, B..............Z)
Lowercase ( ie a, b ................z)
Digits 0, 1, 2 ................... 8, 9
Special symbols +, -, *, ( ) , etc.
Characteristics of C Language
• It is a small programming language that consumes less space.
• It has enough number of inbuilt functions and operators.
Keyword:
The character set consists of alphabet, digit or special symbols used to response information.
There are 32 characters in C:
Auto, If, While, For, Int, float. etc.
Data type:
Data type refers to the type of data or variable which is to be stored and used in the program.
List of data types
• Integer (int) = 2 bytes
• character (char) = 1 byte
• float (float) = 4 bytes
• double (long integer) = 8 bytes
Difference between QBASIC and C-Language
Q-BASIC C- Language
It is a high level language without feature of low level language. It is high level language with some features of low level language.
It is mostly used for designing application software. It is mostly used for designing system software.
Operators
Operators are the symbols which are used to compute values and test multiple operations. The data on which the operators are performed are known as operands.
Types of operator
• Arithmetic operator: The operators which perform mathematical expressions like addition, subtraction, multiplication and division.
• Relational operator: Relational operators are symbols used to compare two different expressions. The result of the comparison is either True or False.
• Logical operator: Logical operators performs tests on multiple relation. Example: A < B and A > B
• Unary operator: C also supports two very important operators called increment and decrement operators.
Loop
A loop causes a section of a program to be repeated a certain number of times. The repetition continues while the condition set for it remains true. When the condition becomes false, the loop ends the control is passed to the statement following the loop.
Variable
Those value which changes during program execution is called variable.Example: A = 5 where A is a variable
Constant
Those values which can't change during the program execution is called constant. Example: A = 10 where 10 is a constant
Rule for naming variables in C
• Space is not allowed in variable name.
• Both upper and lower case letters are permitted.
Printf: This statement is used to display the message on the screen.
Scarf: This statement is used to accept a value.
No comments:
Post a Comment