quick basic programming

Views:
 
Category: Education
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Slide 1: 

Introduction * In This session we will see MicroSoft’s QBasic , BASIC interpreter and program development environment. * The QBasic interpreter has a simple user interface and a menu structure. * Its design serves to aid the user in developing programs with the least number of steps. * The intelligent editor checks syntax as the program lines are entered.

Slide 2: 

Introduction * The program is compiled as it is typed , Allowing the program to be run in a single step. * Errors are identified and reported in a way that allows the user to correct them imediatiately. * This representation is designed for the Beginner as well as Professional. It is also designed to serve as a tool for class room instructure.

Slide 3: 

QBasic Language Qbasic – Language First Session

Slide 4: 

Topics 1. Introduction to ` Qbasic ` 2. History of QB - Language 3. Structure of a QB-program 4. Sample QB program 5. Programming Process 6. Using Qbasic Editor

Slide 5: 

1. Introduction ( – Language ) Qiuck Beginner All Purpose Symbolic Instruction Code - QB is a general-purpose structured programming language. Its instructions consist of terms that resemble to our normal English language keywords e. g. if, for, do, while etc. - QB has a wide variety of library functions - QB is a flexible language. - QB is a highly portable language - QB has a rich family of operators - QB is a user friendly language

Slide 6: 

Qbasic as a replacement for GWBASIC & BASICAis a user friendly , includes : * full screen syntax checking editor * multifile & multi window editing * No compiling step * Full debuging facilities * pull down menues , simple but powerfull menu structure can be selected by using either Key Board or Mouse. 2. History of Qbasic

Slide 7: 

- This session introduces Microsoft’s Qbasic BASIC INTERPRETER. - it also familarizes with user interface and MENU structure of QBasic’s integreted environment. - In this session : 3. Sample session with QBASIC * Type a Program into Qbasic Editor* Run the Program * Save the Program* Quit QBasic

Slide 8: 

3. Structure of a QBasic Program (Contd…) 1. heading . 2. body . Qbasic editor is a full screen , context sensitive , syntax sensitive and self – correcting tool for writing programs. Using the editor is one of the simplest tasks. Each program must contain :

Slide 9: 

4. Sample QBasic Program REM MY FIRST QBASIC PROGRAM CLS PRINT “WEL COME TO QBASIC PROGRAMMING” PRINT “This is my first QBasic program ” END * To Enter Program Simply Starts Typing.* At end of each line press Enter Key.* Now , Type the following Program :

Slide 10: 

- The process of developing a computer program to solve a specific problem involves the following steps : Step : 1 : Problem Definition Step : 2 : Program Design Step : 3 : Program Coding Step : 4 : Program Execution Step : 5 : Program Testing and Debugging Step : 6 : Program Documentation 5. Programming Process

Slide 11: 

- You have to know at least the following things in your mind while using Qbasic Editor. 6. Using Qbasic Editor  About Menu Options  Editor Commands  Hot keys

Slide 12: 

6. Using Qbasic Editor

Slide 13: 

4. Sample QBasic Program ( Running a Program …) REM MY FIRST QBASIC PROGRAM CLS PRINT “WEL COME TO QBASIC PROGRAMMING” PRINT “This is my first QBasic program ” END * To RUN Program Press Shift + F5 Key. - If Qbasic detects any errors , program will not RUN - Qbasic Highlights the program line where error occurred - Display a window on screen regarding Error Description * If No Errors then , Notice the Program OutPut on the Screen* Press SPACE BAR to go back to Qbasic Editor

Slide 14: 

4. Sample QBasic Program ( Saving a Program …) REM MY FIRST QBASIC PROGRAM CLS PRINT “WEL COME TO QBASIC PROGRAMMING” PRINT “This is my first QBasic program ” END * To SAVE Program Press Alt- F Key. * Notice TWO different SAVE Selection: SAVE : it saves the file , if file created is new it ask for file name. SAVE AS : it saves file under new name * Type FILE NAME i.e. TEST.BAS * Press ENTER KEY to save a file. * To QUIT QBasic Program : - Press Alt- FX Key.

Slide 15: 

Character Set Character Meaning 0– 9, a to f,A to F Number decimal Digits/Hex A,B,…,Z Uppercase Letters a,b,…,z Lowercase Letters ! Exclamation point “ Double quotes ‘ Single quote , Comma & Ampersand sign # Number/pound/hash sign

Slide 16: 

Character Set (Continued…) Character Meaning * + - / % \ ^ Arithmetic operator $ Dollor sign : Colon _ Under Score ? Question Mark . Decimal point ; Semi colon > < = Less than / greater than/Equal and so on…..

Slide 17: 

Data Type Data is differentiate into various types. The type of data element restricts the data element to assume a particular set of values. The Basic data types are : String (STR) characters (from character set) Integer ( INT ) an integer long ( LNG ) an integer with higher range Single ( SGL ) a single-precision floating-point Double ( DBL) a double-precision floating-point

Slide 18: 

IDENTIFIER Identifiers are names given to various program elements , such as , variable,constant, arrays , functions, sub-program etc… They are further classified into : * Variable * ConstantReserved word : There are certain reserved words , called Keywords, that have standard , predefined meanings in Qbasic. These Keywords can be used only for their intended purpose , they cannot be used as programmer defined identifiers.

Slide 19: 

Constant A Constant is an entity whose value does not change during execution of program.They are either Literal Constant or Symbolic Constant. Constants are of different types : [1] Integer Constant Decimal / Hexa Decimal [2] Long integer Constant [3] Floating-point Constant [4] String Constant Following are Symbolic Constant : CONST PI = 3.14 CONST MAXN = 10 CONST TITLE$ = “SIR/MADAM” , ADD1$ = “Dear” + TITLE$ , STATE$ = “GUJARAT” , CITY$ = “SURAT” Following are Literal Constant : 3.14 “Today’s Appointment:” 10 “SIR / MADAM” An Integer(Decimal) value within range : –32768 to +32767 ( optional sign prefix ) A Integer (Hex) value within a range : &h0 to &hFFFF ( with prefix &h or &H ) An Integer( Octal) value within range : &o0 to &o177777 ( with prefix &o or &O ) An Long Integer(Decimal) value within range : –2,147,483,648 to +2,147,483,647 A Long Integer (Hex) value within a range : &H0& to &HFFFFFFFF& ( Required Suffix & ) An Long Integer( Octal) value within range : &O0& to &O37777777777& (Required Suffix &) Positive or Negitive numbers in exponintial form Single Precision :- : Range -3.37E+38 to 3.37E+38. Double Precision :- : Range -1.67D+308 to 1.67D+308. String : 1 or more characters enclosed in doble quotes. Include all characters in the ASCII set except : double quotes , carrige return , line feed characters. The Maximum number of characters allowed in a string is 32,767.

Slide 20: 

Variable * A variable is a reference that can change its value during the execution of a program.* In Qbasic variables can be of the basic data types or user defined data type. * A variable name is used to refer to a value. * In Qbasic variables can be DECLARE using : - Data type Charater - DIM statement - TYPE … END TYPE statement etc… - DEFtype statement Variable Name Declaration uses : Suffix Data Type $ String % Integer & Long Integer ! Single Precision # Double Precision i.e. RADIOUS = 10 : MAXAMT% = 1000 PROMPT$ = “ENTER YOUR CHOICE : “ SYNTEX : DIM variable [AS type ] [,variable [AS type] ...] where variable: name of variable AS type : basic data typeDIM A AS INTEGER, NAME AS STRING, AGE AS INTEGER - Defines a data type containing one or more elements. Syntax : TYPE usertype elementname AS typename [elementname AS typename] ... END TYPE i.e. Usertype : The name of the data type being defined. The name can consist of up to 40 characters and must begin with a letter. Valid characters are A-Z, 0-9, and period (.). elementname :An element of the user- defined data type. typename :The element's type (INTEGER, LONG, SINGLE, DOUBLE, STRING, or a user-defined data type). TYPE student_info rollno string name string age integer percentage single class string END TYPE DIM STU_REC AS student_info Uses of Variable : Temporary storage of data Storage of data during computation Menu choice by the user Running counter for loops Reading data from devices Writing data to devices etc... Variable Name : * can be 1 to a maximum of 40 characters long * must begin with a letter ( A..Z , a..z ) * cannot contain other than letters ,numbers ,period and type declaration characters( $,%,#,&,! ) * cannot begin with FN unless it is a function. * cannot be a reserved word.( CLS , PRINT,DIM …) i.e. : I , N , NAME$ , RADIUS … - Sets the default data type for variables. Syntax : DEFINT letterrange [,letterrange]... DEFLNG letterrange [,letterrange]... DEFSNG letterrange [,letterrange]... DEFDBL letterrange [,letterrange]... DEFSTR letterrange [,letterrange]... % --> integer(INT) & --> long integer(LNG) ! --> single(SGL) # --> double(DBL) $ --> string(STR) For Example : DEFDBL A-Q DEFSGL R - X a = SQR(3) PRINT "Square root of 3 = "; a END

Slide 21: 

Constant & Variable (Program…) In Qbasic variables can be DECLARE using : - Data type Charater - DIM statement - TYPE … END TYPE statement etc… A program to demonstrate use of CONSTANT and VARIABLE declaration. * Example 1 * Example 2 * Example 3 REM A PROGRAM TO DEMONSTRATE USE OFREM DATA TYPE CHRATCER CLS NAME$ = "SHREEJI COUNSALTANCY SERVICE" RANK% = 21 PRINT NAME$, RANK% END REM A PROGRAM TO DEMONSTRATE USE OFREM DIM STATEMENTDIM CMPNAME AS STRINGDIM RANK AS INTEGERCLSCMPNAME = "SHREEJI COUNSALTANCY SERVICE“RANK = 21PRINT CMPNAME, RANKEND REM A PROGRAM TO DEMONSTRATE USE OFREM TYPE .. END TYPE STATEMENTTYPE STUDENT ROLLNO AS INTEGER STUNAME AS STRING * 25 CLASS AS STRING * 10 PERCNT AS SINGLEEND TYPEDIM STUDREC AS STUDENTCLSSTUDREC.ROLLNO = 101 STUDREC.STUNAME = "PATEL AXAY M." STUDREC.CLASS = "FIRST" STUDREC.PERCNT = 65 PRINT "ROLL No : "; STUDREC.ROLLNO PRINT " NAME : "; STUDREC.STUNAME PRINT " CLASS : "; STUDREC.CLASS PRINT " % : "; STUDREC.PERCNT END

Slide 22: 

CLS Statement CLS Statement : Clears the screen. Syntex : CLS [{0 | 1 | 2}]i.e. CLS : Clears either the text or graphics viewportCLS 0: Clears the screen of all text and graphicsCLS 1: Clears the graphics viewport or the entire screen if no graphics viewport has been set CLS 2: Clears the text viewport

Slide 23: 

REM Statement REM Statement : Allows explanatory remarks to be inserted in a program Syntex : REM text Or ‘ text* Remarks are ignored when the program runs unless they contain metacommands * A remark can be inserted on a line after an executable statement if it is preceded by the single-quote (') form of REM or if REM is preceded by a colon(:).

Slide 24: 

LET Assignment Statement Consider the following statement : COUNT = COUNT + 1 ; Equivalent to LET COUNT =COUNT+ 1 Example : DIM COUNT AS INTEGER DIM TOTAL AS SINGLE LET COUNT = 15 LET TOTAL = 10 print “ Total = ”;TOTAL LET TOTAL = TOTAL +COUNT print “ Total = ”;TOTAL END Total = 10 Total = 10+15 = 25 LET Statement : LET Statement is used to assign a value to a variable. The value can be an expression or a literal. And must be the same type as variable.. Syntax : [LET] variable = expression For Example : LET a = 10 : LET b = 5 LET area = 0.5 * BASE * HEIGHT LET QUE$ = “HOW ARE YOU ? “

Slide 25: 

Arithmetic Operator QBasic provides ARITHMETIC operators for comparing the values of two expressions. Expression1 Expression2 Arithmetic Operator Arithmetic Expression

Slide 26: 

Relational Operator QBasic provides six relational operators for comparing the values of two expressions expression . Expression1 Expression2 Relational Operator Relational Expression

Slide 27: 

Logical Operator QBasic provides three logical operators for joining two or more relational expressions. Rel. Exp1. Rel. Exp2. Logical Operator Logical Expression

Slide 28: 

Logical AND Operator Exp1 Exp2 Exp1 AND Exp2 AND - Operator will produce result as true only if two operand has true value

Slide 29: 

Logical OR Operator Exp1 Exp2 Exp1 OR Exp2 OR - Operator will produce result as false only if two operand has false value

Slide 30: 

Logical NOT Operator Exp. NOT Exp.

Slide 31: 

LOCATE Statement LOCATE : LOCATE moves the cursor to a specified position on the screen. CSRLIN : returns the current row position of the cursor. POS : returns the current column position of the cursor. Syntax : LOCATE [row%] [,[column%] [,[cursor%] [,start% [,stop%]]]] CSRLIN POS(expression) row% and column% The number of the row and column to which the cursor moves. cursor% Specifies whether the cursor is visible: 0 = invisible, 1 = visiblestart% and stop% Integer expressions in the range 0 through 31 that specify the first and last cursor scan lineYou can change the cursor size by changing the cursor scan lines. expression Any expression. REM Example of LOCATE STATEMENT CLS LOCATE 5, 5 MyRoW% = CSRLIN MyCol% = POS(0) PRINT "Position 1: "; MyRoW%; MyCol% LOCATE (MyRoW% + 2), (MyCol% + 2) MyRoW% = CSRLIN MyCol% = POS(0) PRINT "Position 2: "; MyRoW%; MyCol% END OUTPUT Position 1 : 5 5 Position 2 : 7 7

Slide 32: 

GOTO STATEMENT GOTO Statement is an Unconditional branch. i.e. Program control will continue with the line or label that the GOTO references.- The Unconditional branch can only be at the same lavel as the GOTO statement.- You cannot use GOTO to enter or exit a subroutine or function. Syntax : GOTO line number / line label For Example : QBasic Reserved Word A Valid Line Number i.e. 0 to 65529 A Valid Line Label , String with a letter A Valid Line Label , String with a letter can’t exceed 40 characters in length and always termineted with colon

Slide 33: 

PRINT STATEMENT PRINT : PRINT writes data to the screen or to a file.LPRINT: prints data on the printer LPT1. Syntax:PRINT [#filenumber%,] [expressionlist][{; | ,}] LPRINT [expressionlist] [{; | ,}] filenumber% : The number of an open file.If you don't specify a file number, PRINT writes to the screen. expressionlist: A list of one or more numeric or string expressions to print. {; | ,} Determines where the next output begins:Where ; means print immediately after the last value., means print at the start of the next print zone.Print zones are 14 characters wide. Example : REM example of print statement DIM i AS INTEGER DIM s AS SINGLE DIM stg AS STRING i = 123 s = 123.3456 stg = “computer” CLS PRINT "PRINT i : "; PRINT I PRINT "PRINT s : "; PRINT s PRINT "PRINT stg : "; PRINT stg END PRINT i : 123 PRINT s : 123.3456 PRINT stg : computer

Slide 34: 

PRINT USING STATEMENTFORMATTED OUTPUT PRINT USING : PRINT USING writes FORMATTED OUTPUT to the screen or to a file. LPRINT USING : LPRINT USING writes FORMATTED OUTPUT on LPT1 PRINTER Syntax: PRINT [#filenumber%,] USING formatstring$; expressionlist [{; | ,}] LPRINT USING formatstring$; expressionlist [{; | ,}] numeric expression # Digit position. . Decimal point position. , Placed left of the decimal point, prints a comma every third digit. + Position of number sign. ^^^^ Prints in exponential format. - Placed after digit, prints trailing sign for negative numbers $$ Prints leading $.** Fills leading spaces with *. **$ Combines ** and $$. String expression & Prints entire string.! Prints only the first character of string\ \ Prints first n characters, where n is the number of blanks between slashes + 2 Data Type Suffix ! Single-precision % Integer # Double-precision & Long-integer $ String DIM i AS INTEGER , s AS SINGLE , d AS DOUBLE DIM l AS LONG , stg AS STRING i = 123 : s = 123.3456 : d = 12345.678# l = 987667896 : stg = "computer" CLS PRINT "PRINT i : "; PRINT i PRINT "PRINT USING +###; i : "; PRINT USING "+###"; i PRINT "PRINT USING ####.####+; s : "; PRINT USING "#,##,#.####+"; s PRINT "PRINT s : "; PRINT s PRINT "PRINT USING ####.####^^^^ ; s : "; PRINT USING "########.####^^^^"; s PRINT "PRINT USING ####.####^^^^ ; d : "; PRINT USING "########.####^^^^"; d PRINT "PRINT l : "; PRINT l PRINT "PRINT USING ####.####^^^^ ; l : "; PRINT USING "########.####^^^^"; l PRINT "PRINT stg : "; PRINT stg PRINT "PRINT USING & ; stg : "; PRINT USING "&"; stg PRINT "PRINT USING ! ; stg :"; PRINT USING "!"; stg PRINT "PRINT USING \\; stg :"; PRINT USING "\\"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg PRINT "PRINT USING \ \; stg : "; PRINT USING "\ \"; stg END

Slide 35: 

END , STOP STATEMENT END STATEMENT :Ends a program , procedure, block, or user-defined data type. Syntax : END [{DEF | FUNCTION | IF | SELECT | SUB | TYPE}] END DEF : Ends a multiline DEF FN function definition. END FUNCTION : Ends a FUNCTION procedure definition. END IF : Ends a block IF...THEN...ELSE statement. END SELECT : Ends a SELECT CASE block. END SUB : Ends a SUB procedure. END TYPE : Ends a user-defined data type definition. If no argument is supplied, END ends the program and closes all files. EXAMPLE : CLS PRINT "WELCOME TO QBASIC " PRINT "PROGRAM over." END

Slide 36: 

STOP STATEMENT STOP STATEMENT : Halts a program. 'STOP pauses; F5 Continues. Syntax : STOP Example: FOR i% = 1 TO 10 PRINT i% IF i% = 5 THEN STOP NEXT i% END

Slide 37: 

Library Function mathetical function : 1. abs 2. int 3. cos 4. sin 5. tan 6. sqr 7. sgn 8. exp 9. val 10. swap

Slide 38: 

String What is a String ? - A string is an group of characters. - Any group of characters (except double quote sign) defined between double quotation marks is a constant string. For Example : “This is a string”

Slide 39: 

String (Contd..) Character string are often used to build meaningful and readable programs. The common operations performed on character strings are : - Reading and Writing strings - Combining string together - Comparing strings for equality - Extracting a portion of a string etc.

Slide 40: 

String (Contd..) How to Declare a String Variable ? A string variable is any valid QBasic variable name and is always declared as of type STRING. The general form of a string variable is : DIM str_name AS STRING [* size ] The size determines the number of characters in the string-name.

Slide 41: 

Library Function String function : 1. SPACE$(n%) : Returns a string of spaces. Syntax : SPACE$(n%) where n% is the number of spaces you want in the string. Example : REM USE OF SPACE$ FUNCTION DIM I AS INTEGER CLS PRINT " USE OF SPACE$ FUNCTION" FOR I = 1 TO 5 PRINT SPACE$(I); I NEXT I END OUTPUT USE OF SPACE$ FUNCTION 1 2 3 4 5 FOR I = 1 TO 5 PRINT SPACE$(I); I NEXT I

Slide 42: 

Library Function (Cont.) String function : 2. SPC : Skips a specified number of spaces in a PRINT/LPRINT statement. Syntax : SPC(n%) Where n% is number of spaces to skip; a value in the range 0 through 32,767. Example : REM USE OF SPC FUNCTION CLS PRINT "USE OF SPC FUNCTION " PRINT "Text1"; SPC(10); "Text2" FOR I = 1 TO 5 PRINT SPC(I); I NEXT I END OUTPUT USE OF SPC FUNCTION Text1 Text2 1 2 3 4 5 FOR I = 1 TO 5 PRINT SPC(I); I NEXT I

Slide 43: 

Library Function (Cont.) String function : TAB : Moves the text cursor to a specified print position. Syntax : TAB(column%) Where column% : The column number of the new print position. Example : CLS PRINT "USE OF TAB FUNCTION " PRINT TAB(25); "Text" FOR I = 1 TO 5 PRINT TAB(I); I NEXT I END OUTPUT USE OF TAB FUNCTION 25th Text1 1 2 3 4 5 FOR I = 1 TO 5 PRINT TAB(I); I NEXT I

Slide 44: 

Library Function (Cont.) ASC : returns the ASCII code for the first character in a string expression. CHR$ : returns the character corresponding to a specified ASCII code. Syntax : ASC(stringexpression$) CHR$(ascii-code%) Where stringexpression$ : Any string expression. ascii-code% : The ASCII code of the desired character. Example: PRINT ASC("Q") 'Output is: 81 PRINT CHR$(65) 'Output is: A

Slide 45: 

Library Function (Cont.) 4. string$ : Returns a string of a specified length made up of a repeating character. Syntax : STRING$(length%,{ascii-code% | strexpression$}) Where length% : The length of the string. ascii-code% : The ASCII code of the repeating character. strexpression$ : Any string expression. STRING$ fills the string with the first character in stringexpression$. Example : CLS PRINT " USE OF STRING$ FUNCTION" PRINT STRING$(25, "-") PRINT "Hello ! WEL COME ...!" PRINT STRING$(25, 52) END OUTPUT USE OF STRING$ FUNCTION ----------------------- Hello ! WEL COME ... ! 44444444444444444444444

Slide 46: 

Library Function (Cont.) 5. LEN : Returns the number of characters in a string or the number of bytes required to store a variable. Syntax : LEN(stringexpression$) LEN(variable) Where stringexpression$ : Any string expression. variable : Any nonstring variable. Example : REM Example: ANS : LEN = 16 CLS DIM a AS STRING a = "Microsoft QBasic" PRINT a PRINT PRINT "Length of string = "; LEN(a) END OUTPUT Microsoft QBasic Length of string = 16

Slide 47: 

DATA & READ Statement * DATA specifies values to be read by subsequent READ statements. * READ reads those values and assigns them to variables. * RESTORE allows READ to reread values in specified DATA statements. Syntax : DATA constant[,constant]... READ variablelist RESTORE [line] * if a symbolic constant ( defined in a CONST statement ) appears in a DATA statement : - That constant is interpreted as a string value , Not as the value defined in the CONST statement. For Example : CONST Maxlist = 200 … READ Val1,Val2 … DATA 100,Maxlist IF a READ statement is executed, the second data item is interpreted as a string constant (Maxlist) , Not as numeric constant 200 DATA statement is used only with the READ statement.Thus it must appear at least once in a program with a READ statement. DATA statement can contain as many Constant as will fit on one line. Several DATA statements may appear one after another. DATA statements can contain more values than are required by the READ statement. READ statement continues from the last UNREAD data item on list. DATA statement should contain at least as many data items as there are variables in . DATA statement can contain as many Constant as will fit on one line. Several DATA statements may appear one after another. DATA statements can contain more values than are required by the READ statement. READ statement continues from the last UNREAD data item on list. Data statement should contain at least as many data items as there are variables in READ statement. IF there fewer data items than variables, a run-time error occurs. REM A program which will use DATA & READ St. TYPE EMPLOYEE EMPNO AS STRING * 5 EMPNAME AS STRING * 25 DEPT AS STRING * 15 REMARK AS STRING * 15 END TYPE DIM NEWEMP AS EMPLOYEE READ NEWEMP.EMPNO , NEWEMP.EMPNAME , NEWEMP.DEPT CLS PRINT “This is a demonstration of the DATA statement “ PRINT : PRINT PRINT “EMPLOYEE NUMBER : “;NEWEMP.EMPNO PRINT “EMPLOYEE NAME :”;NEWEMP.EMPNAME PRINT “ DEPARTMENT :”;NEWEMP.DEPT PRINT “ REFERENCE :”;NEWEMP.REMARK PRINT DATA 101 ,PATEL S.R. , EDUCATION END This is a demonstration of the DATA statement EMPLOYEE NUMBER : 101 EMPLOYEE NAME : PATEL S.R. DEPARTMENT : EDUCATION REFERENCE : NOTE : DATA 101 ,PATEL S.R. , EDUCATION A LIST OF VARIABLES SEPARATED BY COMMAS INTO WHICH DATA IS READ. THE VALUES FROM THE DATA STATEMENT ARE ASSIGNED IN A ONE-TO-ONE RELATION.

Slide 48: 

INPUT STATEMENT INPUT : reads input from the keyboard or file.LINE INPUT : reads a line of up to 255 characters from the keyboard or file. Syntax : INPUT [;] ["prompt"{; | ,}] variablelist LINE INPUT [;] ["prompt";] variable$This is one of the most commonly usedmethods in QBasic for entering values of variables. NOTE : INPUT uses a comma as a separator between entries. LINE INPUT reads all characters up to a carriage return. For keyboard input, a semicolon immediately after INPUT keeps the cursor on the same line after the user presses the Enter key. INPUT can be accepted into STRING , NUMERIC , ARRAY, and RECORD ELEMENTS. Example: CLS INPUT " NAME : ", Name$ 'Read entries from the kb’d. INPUT " AGE : ", Age$ PRINT PRINT " NAME : "; Name$ PRINT " AGE : "; Age$ END IF VALUE ENTERED WAS OF INCORRECT TYPE OR TOO MANY OR TOO FEW VALUES WERE ENTERED THENCOMPILER GIVES FOLLOWING ERROR“REDO FROM START”

Slide 49: 

Conditional Statement A Conditional statement allows selective processing of a statement or a group of statements. There are two forms of conditional statement : [1] if-then-else statement [2] if-then-elseif … else statement

Slide 50: 

Simple if statement Purpose : It is used to test the condition or to take decision. Sometimes it is also referred as decision-making statement. Syntax : if (expression) then statement if (expression) then statement [else statement ]

Slide 51: 

How simple if statement work ? Consider the following simple-if statement. if (n MOD 2 <> 0 ) then print “ It is an odd number” Keyword Relational Operator

Slide 52: 

Operation of the if statement Start

Slide 53: 

If-then-else statement Purpose : Allows conditional execution of a group of statements. However, their are many situations when two groups of statements are given and it is desired that one of them be executed if some condition is true and the other be executed if the condition is false. In such situations, we make use of the if-else statement whose general format is : Syntax : IF condition1 THEN [statementblock-1] [ELSEIF condition2 THEN [statementblock-2]] ... [ELSE [statementblock-n]] END IF Statementblock-1 may be a single statement or a group of statements. It is executed only if the condition1 is true. Statementblock-2 may be a single statement or a group of statements. It is executed only if the condition2 is true. Statementblock-n may be a single statement or a group of statements. It is executed only if the all conditions becomes false.

Slide 54: 

REM DIM NUM AS INTEGER CLS INPUT “ Enter any number : “; NUM if (num MOD 2 = 0 ) then print “Even ” else print “Odd ” end if END If-then-else statement Examples… Condition or Expression resulting in either True or False Value. Only one statement or function or expression. This is an action part for False value Only one statement or function or expression. This is an action part for True value

Slide 55: 

Some more examples DIM i AS INTEGER INPUT "1 or 2? ", i IF i = 1 OR i = 2 THEN PRINT "OK“ ELSE PRINT "OUT OF RANGE“ GOTO ENDPROG IF i = 1 OR i = 2 THEN PRINT "OK“ ELSE PRINT "Out of range“ END IFENDPROG: PRINT "END OF PROG“ END

Slide 56: 

SELECT CASE statement When one of the many alternatives is to be selected , we can design a program using if statement to control the selection. However, the complexity of such a program increases dramatically when the number of alternatives increases. The program become difficult to read and follow. Some times it may even confuse the person who designed it.

Slide 57: 

SELECT statement (Contd…) In ‘QBasic’, there is a built-in multi-way decision statement, which is known as SELECT CASE statement. The SELECT CASE statement tests the value of a given variable/expression against a list of case values and when a match found, a block of statements associated with that case is executed.

Slide 58: 

switch statement (Contd…) The general form of the SELECT CASE statement is as shown below : SELECT CASE (testexpression) CASE expressionlist1 [statementblock-1] [CASE expressionlist2 [statementblock-2]] ... [CASE ELSE [statementblock-n]] END SELECT testexpression is Any numeric or string expression expressionlist1 : One or more expressions toexpressionlist2 match testexpression. The IS keyword must precede any relational operators in an expression statementblock1 : One or more statements onstatementblock2 one or more lines ...statementblockn The expressionlist arguments can have any of the following forms or a combination of them, separated by commas: 1. expression[,expression]... 2. expression TO expression 3. IS relational- operator expression expression : Any numeric or string expression compatible with testexpression. relational-operator : One of thefollowing relational operators: <, <=, >, >=, <>, or =

Slide 59: 

SELECT statement (Example ) DIM A, B AS SINGLE, OP AS STRING INPUT "Enter A B OP : ", A, B, OP SELECT CASE OP CASE IS = "+" PRINT " ADDITION " RESULT = A + B PRINT "RESULT = "; RESULT CASE IS = "-" PRINT " SUBTRACTION " RESULT = A - B PRINT "RESULT = "; RESULT CASE IS = "*" PRINT " MULTIPLCATION " RESULT = A * B PRINT "RESULT = "; RESULT CASE IS = "/" PRINT " REAL DIVISION " RESULT = A / B PRINT "RESULT = "; RESULT CASE IS = "\" PRINT " INTEGER DIVISION " RESULT = A \ B PRINT "RESULT = "; RESULT CASE ELSE PRINT "INVALID OPERATOR " END SELECT END

Slide 60: 

SELECT statement (Example ) REM A PROGRAM TO FIND ROOTS OF QUADRATIC EQUATION REM Ax^2 + Bx + C = 0 CLS DIM A, B, C, DELTA AS SINGLE INPUT "Enter A B C : ", A, B, C DELTA = B * B - 4 * A * C PRINT "DELTA = "; DELTA SELECT CASE DELTA CASE IS > 0 PRINT "DELTA > 0 " CASE IS < 0 PRINT "DELTA < 0" CASE IS = 0 PRINT "DELTA = 0" END SELECT END PRINT "TWO ROOTS" ROOT1 = (-B - SQR(DELTA)) / (2 * A) ROOT2 = (-B + SQR(DELTA)) / (2 * A) PRINT "ROOT1 = "; ROOT1 PRINT "ROOT2 = "; ROOT2 PRINT "COMPLEX ROOTS " RPART = -B / (2 * A) IPART = SQR(ABS(DELTA)) / (2 * A) PRINT "REAL PART = "; RPART PRINT "IMMEGINARY PART = "; IPART PRINT "BOTH ROOTS ARE SAME" ROOT1 = -B / (2 * A) ROOT2 = -B / (2 * A) PRINT "ROOT1 = "; ROOT1 PRINT "ROOT2 = "; ROOT2

Slide 61: 

Library Function (Cont.) 6. MID$ FUNCTION / STATEMENT * MID$ function returns part of a string ( a substring ). * MID$ statement replaces part of a string variable with another string. SYNTAX : MID$( stringexpression$, start% [,length% ]) MID$( stringvariable$ ,start%[,length%])= stringexpression$ Example: CLS PRINT " USE OF MID$ FUNCTION / STATEMENT " PRINT : PRINT " USE OF MID$ FUNCTION" a$ = "Where is Valod?" PRINT MID$(a$, 10, 5) Text$ = "Valod , Bardoli" PRINT Text$ 'Output is: Valod , Bardoli PRINT " USE OF MID$ STATEMENT " MID$(Text$, 9) = "Navsari" PRINT Text$ 'Output is: Valod , Navsari PRINT : PRINT a$: PRINT FOR I = 1 TO LEN(a$) STEP 1 PRINT SPC(I); I; "-------> "; MID$(a$, I, 1) NEXT I END Bardoli Navsari

Slide 62: 

Library Function (Cont.) 7. left$ and right$ : Return a specified number of leftmost or rightmost characters in a string. Syntax : LEFT$(stringexpression$,n%) RIGHT$(stringexpression$,n%) stringexpression$ : Any string expression. n% : The number of characters to return, beginning with the leftmost or rightmost string character. Example: CLS PRINT "USE OF LEFT$ / RIGHT$ " a$ = "Microsoft QBasic" PRINT "Given String : "; a$ PRINT LEFT$(a$, 5) 'Output is: Micro PRINT RIGHT$(a$, 5) 'Output is: Basic END

Slide 63: 

Library Function (Cont.) 8. LCASE$ and UCASE$ : Convert strings to all lowercase or all uppercase letters. Syntax : LCASE$(stringexpression$) UCASE$(stringexpression$) stringexpression$ : Any string expression. Example: CLS PRINT "USE OF LCASE$ / UCASE$ " a$ = "Microsoft QBasic" PRINT "Given String : "; a$ PRINT LCASE$(a$) 'Output is: microsoft qbasic PRINT UCASE$(a$) 'Output is: MICROSOFT QBASIC END Microsoft QBasic

Slide 64: 

Library Function (Cont.) 9. LRTIM$ / RTRIM$ : Remove LEADING / TRAILING spaces from a string. SYNTAX : LTRIM$(stringexpression$) RTRIM$(stringexpression$) stringexpression$ : Any string expression. Example: CLS PRINT "USE OF LTRIM$/RTRIM$ " a$ = " Basic " PRINT "ORIGINAL STRING ": PRINT PRINT "*" + a$ + "*" 'Output is: * Basic * PRINT " USE OF LTRIM$ ": PRINT PRINT "*" + LTRIM$(a$) + "*" 'Output is: *Basic * PRINT " USE OF RTRIM$ ": PRINT PRINT "*" + RTRIM$(a$) + "*" 'Output is: * Basic* END

Slide 65: 

Library Function (Cont.) 10. STR$ : Returns a string representation of a number. VAL : Converts a string representation of a number to a number. Syntax : STR$(numeric-expression) VAL(stringexpression$) Where numeric-expression : Any numeric expression stringexpression$ : A string representation of a number Example: CLS PRINT "Decimal 65 is represented in hexadecimal as "; PRINT "&H" + LTRIM$(STR$(41)) PRINT VAL(RIGHT$("Microsoft 1990", 4)) END Decimal 65 is represented in hexadecimal as = &H41 1990

Slide 66: 

Library Function (Cont.) 11. time$ function / statement : TIME$ function returns the computer‘s current system time in the form hh:mm:ss. TIME$ statement sets the current system time on your computer. Syntax : TIME$ TIME$ = stringexpression$ stringexpression$ : The time in one of the following forms: hh Sets the hour; minutes and seconds default to 00. hh:mm Sets the hour and minutes; seconds default to 00. hh:mm:ss Sets the hour, minutes, and seconds. Example: CLS ‘TIME$ function Return time PRINT TIME$ TIME$ = "08:00:00" ‘TIME$ Statement change time to ‘ new time 08:00:00 ‘The new system time remains in ‘effect until you change it ‘again. PRINT "Time set to "; TIME$ ‘Display new time END

Slide 67: 

Library Function (Cont.) 12. date$ function / Statement DATE$ function :returns the computer's current system date. DATE$ statement:sets the current system date on your computer. Syntax : DATE$ DATE$ = stringexpression$ Where stringexpression$ : The date in one of the following forms: mm-dd-yy, mm-dd-yyyy, mm/dd/yy, mm/dd/yyyy. The DATE$ function returns a string in the form mm-dd-yyyy. Example: CLS ‘ DATE$ Function Return Date PRINT DATE$ DATE$ = "01-01-2001“ ‘ DATE$ Statement set New Date ‘ The new system date remains in‘ effect until you change it‘ again. PRINT "Date set to "; DATE$ ‘ Display New Date END

Slide 68: 

Library Function (Cont.) 13. inkey$ : Reads a character from the keyboard. Syntax: INKEY$ Where INKEY$ returns a null string if there is no character to return. For standard keys, INKEY$ returns a 1-byte string containing the character read. For extended keys, INKEY$ returns a 2-byte string made up of the null character (ASCII 0) and the keyboard scan code. 'Example: CLS PRINT "Use of INKEY$ function " DO PRINT "Press Esc to exit..." LOOP UNTIL INKEY$ = CHR$(27) ‘27 is the ASCII code for Esc Key END

Slide 69: 

Control Structures To control the flow of execution of programs, the ‘QBasic’ language provides very powerful facilities. There are basically three types of control structures, viz. [1] Sequential [2] Selective or decision making or conditional [3] Repetitive or iterative or looping

Slide 70: 

Repetitive or iterative or program loop structure The repetitive structure allows a sequence of program statements to be executed several times though those statements appear only once in the program. It consists of : * an entry point that may include initialization of certain variables * a loop Continuation Condition * a loop body * an exit point

Slide 71: 

Repetitive or iterative or program loop structure (Continued …) Exit Loop Continuation Condition FORM :-1 PRE-TEST LOOP FORM :-2 POST-TEST LOOP

Slide 72: 

Repetitive or iterative or program loop structure (Continued …) A repetitive structure must always be entered at the entry point to ensure that the appropriate initialization takes place. The loop body consists of statements that are normally executed several times. The exit point is the first statement following the loop body. The number of repetitions in a repetitive structure is controlled by a loop continuation condition, which is tested once for each execution of the loop body.

Slide 73: 

Repetitive or iterative or program loop structure (Continued …) There are Three major loop structure in Qbasic - language [1] for Loop [2] do Loop [2a] do while/until ... Loop [2b] do ... While/until Loop [3] while ... Wend Loop

Slide 74: 

for Loop The for loop is a very flexible and powerful repetitive structure(PRE-TEST LOOP). If you are knowing the number of times a block of statement(s) that you want to execute a specific number of times then for - loop is most appropriate. The general form of the for loop is :

Slide 75: 

for Loop General Form (Continued…) FOR counter = start TO end [STEP increment] [statementblock] NEXT [counter] Where Counter: A numeric variable used as the loop counter. start : The initial and final values of the end counter. Increment: The amount the counter is changed each time through the loop.

Slide 76: 

Operation of for Loop Enter Initialization Body of the loop Increment Test False True Exit FORM :-1 PRE-TEST LOOP

Slide 77: 

Example of for Loop FOR I = 1 TO 5 PRINT I NEXT I FOR I = 7 TO -6 STEP –3 PRINT I NEXT I FOR I = 1 TO 5 STEP .5 PRINT I NEXT I FOR I = 1 TO R FOR J = 1 TO C PRINT I, J; NEXT J PRINT NEXT I

Slide 78: 

Example of for Loop REM 1. PRINT 1st N NUMBER. ALSO CALCULATE SUM & AVG OF N NUMBER CLS DIM I, N, SUM AS INTEGER DIM AVG AS SINGLE INPUT "ENTER N : "; N SUM = 0 FOR I = 1 TO N PRINT I SUM = SUM + I NEXT I AVG = SUM / N PRINT "SUM : "; SUM PRINT "AVERAGE : "; AVG END SUM = 55 AVERAGE =5.5

Slide 79: 

Example of for Loop REM 2 PRINT N,N*N,N*N*N AND ALSO PRINT SUM OF N, N*N , N*N*N. DIM N, SUMN, SUMSQ, SUMCUBE AS SINGLE DIM I AS INTEGER INPUT "ENTER N : "; N PRINT " N N*N N*N*N “ SUMN = 0: SUMSQ = 0: SUMCUBE = 0 FOR I = 1 TO N PRINT I, I * I, I * I * I SUMN = SUMN + I SUMSQ = SUMSQ + I * I SUMCUBE = SUMCUBE + I * I * I NEXT IPRINT "SUMN = "; SUMNPRINT "SUM OF SQUERE = "; SUMSQPRINT "SUM OF CUBE = "; SUMCUBEEND ENTER N : 5 N N*N N*N*N 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 SUM OF N : 15 SUM OF N*N : 55 SUM OF N*N*N : 225

Slide 80: 

Example of for Loop REM 3. CALCULATE FACTORIAL OF N. CLS DIM I, N, FACT AS INTEGER INPUT "ENTER N : "; N FACT = 1 FOR I = 1 TO N FACT = FACT * I NEXT I PRINT “ N! = "; FACT END ENTER N : 5 N! = 120

Slide 81: 

Example of for Loop REM 4. PRINT 1st N TERMS OF ODD / EVEN NUMBER. DIM I, J, N AS INTEGER INPUT "ENTER N "; N PRINT "1 ST N ODD NUMBER ARE AS FOLLOWS “ J = 1 FOR I = 1 TO N PRINT J J = J + 2 NEXT I PRINT "1 ST N EVEN NUMBER ARE AS FOLLOWS “ J = 0 FOR I = 1 TO N PRINT J J = J + 2 NEXT I END ENTER N : 5 1ST N ODD NUMBER ARE AS FOLLOWS : 1 3 5 7 9 ENTER N : 5 1ST N EVEN NUMBER ARE AS FOLLOWS : 0 2 4 6 8

Slide 82: 

Do [ { While |Until } ] - LOOP - The Do while|until loop is a pre-test loop , whose general format is : Do [ { While|Until } ] (expression) body of loop Loop

Slide 83: 

Do While - LOOP - The Do while loop is a pre-test loop , whose general format is : Do [ { While } ] (expression) body of loop Loop

Slide 84: 

Do Until - LOOP - The Do Until loop is a pre-test loop , whose general format is : Do [ { Until } ] (expression) body of loop Loop

Slide 85: 

Do .. [ { While |Until } ] - LOOP - The Do .. while|until loop is a post-test loop , whose general format is : Do body of loop [ { While|Until } ] (expression)

Slide 86: 

Do .. [ { While |Until } ] - LOOP - The Do .. While loop is a post-test loop , whose general format is : Do body of loop [ { While } ] (expression)

Slide 87: 

Do .. [ { While |Until } ] - LOOP - The Do .. until loop is a post-test loop , whose general format is : Do body of loop [ { Until } ] (expression)

Slide 88: 

While .. Wend - LOOP - The While .. Wend loop is a pre-test loop , whose general format is : While (expression) body of loop Wend

Slide 89: 

More example of Do while-loop REM Dim count = 0 cls count = 0 Do while ( count <10 ) print “Count = ”,count count = count+1 Loop END

Slide 90: 

Operation of the while-loop REM Dim count as integer count = 0 do while ( count < 10 ) print “Count = ”, count count = count+1 loop end Enter Body of loop False

Slide 91: 

do - while Loop (Example) REM CLS DIM count as integer count = 0 do print “ Count = ”,count count = count +1 while (count < 10) END

Slide 92: 

do - while Loop (Example) #include <stdio.h> main() { int count=0; do { printf(“\n Count = %d”,count); count = count +1; } while (count<10); } #include <stdio.h> main() { int count=0; do { printf(“\n Count = %d”,count); count = count +1; } while (count<10); } do print “ Count = ”,count count = count +1 while ( count<10) Body of the loop

Slide 93: 

More examples of loop REM Dim count as integer cls count = 1 Do while ( count <=10 ) print “Count = ”,count count = count+1 Loop END REM Dim count as integer cls count = 1 Do Until ( count > 10 ) print “Count = ”,count count = count+1 Loop END REM Dim count as integer cls count = 1 Do print “Count = ”,count count = count+1 While ( count <= 10 ) END REM Dim count as integer cls count = 1 Do print “Count = ”,count count = count+1 Until ( count > 10 ) END REM Dim count as integer cls count = 1 While ( count <= 10 ) print “Count = ”,count count = count+1 Wend END

Slide 94: 

ARRAY What is an Array ? An ordered finite collection of data items, each of the same type, is called an array, and the individual data items are its elements. OR An array is a collection of variables of a certain type, placed contiguously in memory.

Slide 95: 

ARRAY (Continued..) Only one name is assigned to an entire array, and individual elements are referenced by specifying a subscript. A subscript is also called an index. In QBasic , * Subscripts Range : - 32768 to + 32767 * Maximum 60 Dimension are allowed * Array has Maximum Size Limit : 64 K

Slide 96: 

Array Declaration Arrays, like simple variable, need to be declared before use. An array declaration is of the form : DIM array-name( subscript ) AS TYPE subscript : Lower limit TO Upper limit : - 32768 TO + 32767 : Maximum 60 dimension

Slide 97: 

Example of an Array For example, DIM a(6) AS INTEGER a(0) a(1) a(2) a(3) a(4) a(5) a(6) 1st element is referenced by a(0) , 2nd ” a(1) , and so on. 1 2 3 4 5 6 7

Slide 98: 

Example of an Array For example, DIM A(5) or DIM A( 0 TO 5 ) a(0) a(1) a(2) a(3) a(4) a(5) The default Lower bound is zero. 1 2 3 4 5 6

Slide 99: 

Example of an Array For Example , TWO Dimension Array DIM A(5,5) or DIM A( 0 TO 5 , 5) or DIM A(5, 0 TO 5 ) * The default Lower bound is zero. * Maximum 60 Dimension are allowed. * Array has Maximum size Limit : 64 K. When an array referenced with a subscript that is outside the declaration , meaasge “ Subscript out of range “ appears.

Slide 100: 

More about an Array - Array Initialization. - Reading the elements of an array - Processing of an array - Printing an array elements

Slide 101: 

STOP / SYSTEM STATEMENT STOP: Halts a program. Syntax : STOP Example: CLS FOR i% = 1 TO 10 PRINT i% IF i% = 5 THEN STOP 'STOP pauses; F5 Continues. NEXT i% END SYSTEM : Closes all open files and returns control to the operating system. Also close QBASIC program. Syntax: SYSTEM

Slide 102: 

ON ... GOSUB / GOTO Statement ON ...GOSUB / GOTO : Branch to one of several locations,depending on the value of an expression. Syntax : ON expression% GOSUB line-list ON expression% GOTO line-list expression% : An expression in the range 0 through 255 line-list : A set of labels or line numbers. If the value of the expression is 1, the program branches to the first line in the list; if the expression is 2, it branches to the second line, and so on. Note : SELECT CASE provides a better way to perform multiple branching. Example:CLS PRINT Use of ON…GOSUB Statement FOR i% = 1 TO 2 ON i% GOSUB one, Two NEXT i% END one: PRINT "One" RETURN Two: PRINT "Two" RETURN Example:CLS PRINT Use of ON…GOTO Statement FOR i% = 1 TO 2 ON i% GOTO one, Two NEXT i% END one: PRINT "One" STOP Two: PRINT "Two" STOP

Slide 103: 

GOSUB line1 ... RETURN [line2] GOSUB line1 ... RETURN [line2] : Branches to and returns from a subroutine. line1 : The label or line number of the first line of the subroutine. line2 : The label or line number where the subroutine returns. * If you don't supply a label or line number for RETURN,the program continues execution at the statement following the GOSUB (for subroutine calls) or where an event occurred (for event handling). * SUB and CALL statements provide a better alternative to GOSUB subroutines. Example:CLS PRINT "USE OF GOSUB STATEMENT " FOR i% = 1 TO 20 GOSUB Square NEXT i% END Square: PRINT i%, i% * i% RETURN

Slide 104: 

Exit Statement Exit Statement : Exits a DO or FOR loop, a FUNCTION or SUB procedure , or a DEF FNfunction. Syntax : EXIT {DEF | DO | FOR | FUNCTION | SUB} DEF Exits a DEF FNfunction. DO Exits a DO loop. FOR Exits a FOR loop. FUNCTION Exits a FUNCTION procedure. SUB Exits a SUB procedure.

Slide 105: 

Shared / Static Variable Declaration Statement SHARED : Gives procedures access to module-level variables. STATIC : Makes a variable local to a function or procedure and preserves its value between calls. Syntax : SHARED variable[()] [AS type], ... STATIC variable[()] [AS type], ...

Slide 106: 

DEF FN STATEMENT DEF FN STATEMENT : Defines a function. SYNTAX : 1.DEF FNname[(parameterlist)] = expression 2.DEF FNname[(parameterlist)] [statementblock] FNname = expression [statementblock] [EXIT DEF] [statementblock] END DEF

Slide 107: 

DEF FN STATEMENT Continue.. REM DEF FN STATEMENT SYNTAX 1 DEF FNname[(parameterlist)] = expression Example : DEF fndelta (a, b, c) = b * b - 4 * a * c CLS INPUT "Enter a,b,c : "; a, b, c ‘ CALLING FUNCTION D = fndelta(a, b, c) PRINT “DELTA = “;D END

Slide 108: 

DEF FN STATEMENT DEF FN STATEMENT : Defines a function. DEF FNname[( parameterlist )] [statementblock] FNname = expression [statementblock] [EXIT DEF] [statementblock] END DEF

Slide 109: 

DEF FN STATEMENT Continue.. Example : REM DEF FN STATEMENT SYNTAX 2 DEF fnfactorial (n) REM local variables STATIC i, nfact nfact = 1 FOR i = 1 TO n STEP 1 nfact = nfact * i NEXT i fnfactorial = nfact END DEF CLS INPUT "Enter n :"; n fact = fnfactorial(n) PRINT "n! = "; fact END

authorStream Live Help