Title: Basic Programming
1Basic Programming
2Computer Programs
Processing
Input
Output
3Programming Tools
- Flowcharts
- Pseudocode
- Top-down Charts
4Flowcharts
Flowline
Input/Output
Terminal (start/end)
Decision
Processing
5Flowcharts
Start
Read Data
Process Data
Print Result
End
6Pseudocode
- English like description of program steps
- Read number of items and cost
- Multiply cost times number
- Display the number of items, cost, and total
7Top-Down Chart
Program Name
Process Data
Output Results
Read Input Data
8Programming Structures
- Sequential -- One step after another
- Decision Structure -- IF...Then...Else
- Looping Structure -- DO WHILE (or DO UNTIL)
9Sequential Structure
Step 1
Step 2
Step 3
10Decision Structure
Then
Else
IF
Process 2
Process 1
11Looping Structure
NO
True?
YES
Process
12Arithmetic Operations
- Addition
- Subtraction -
- Multiplication
- Division /
- Exponentiation
13Numbers
- Constants -- e.g. 17, 1.329, 1.4E3
- Variables -- Names for areas in memory that can
have different values at different times - Up to 40 characters
- Must begin with a letter of the alphabet
- Only letters, digits, and periods
- Smallest is one letter
14Sample Program
- CLS
- LET rate 50
- LET time 14
- LET distance rate time
- PRINT distance
- LET distance 410
- LET time distance / rate
- PRINT time
- END
15Basic Statements
- CLS -- Clears Screen
- LET -- LET var expression
- PRINT -- PRINT list (use of )
- END -- signifies end of program
16Qbasic
- Type QBASIC at DOS prompt
- Menu Choices
- File Edit View Search Run Debug Options
- Smart editor catches many Syntax errors
- REM is for remarks, such as your name and date
17Programming Exercise
Create and run the following program CLS LET
grade1 3 LET grade2 2 LET grade3
3.25 LET gpa (grade1 grade2 grade3) /
3 PRINT grade1, grade2, grade3 PRINT
gpa END Change values for grades and run again.
18Relational Operators
- equal to
- ltgt not equal to
- lt less than
- gt greater than
- lt less than or equal to
- gt greater than or equal to
19Functions
- Prewritten routines that return a value based
on one or more inputs - Examples
- SQR(expression)
- INT(expression)
- Expression is a number, variable, or calculation
20A Word to the Wise
- Complete as many of the odd number exercises as
you can, checking your answers with those
provided - Get familiar with the mechanics of using the
Qbasic editor
21Strings
- Strings are anything other than numbers
- String constants are enclosed in double quotes
() - String variable names end with a dollar sign ()
22Example of Strings
- CLS
- LET me "Joe Komar "
- PRINT me
- PRINT "is one of the greatest instructors I
have." - LET me "Student name "
- PRINT me
- PRINT "is a great student."
- END
23Strings
- Concatenation
- Use plus sign () between strings
- Get all ASCII characters with the character
string function - CHR(number)
- (see Appendix A for ASCII chart)
24String Relationships
- identical to
- ltgt different from
- lt precedes alphabetically
- gt follows alphabetically
- lt precedes or identical
- gt follows or identical
- (special characters, digits, upper, lower)
25String Related Functions
- LEFT(string, of characters)
- RIGHT(string, of characters)
- MID(string,beginning character,of characters)
- UCASE(string)
- LEN(string)
- INSTR(string,substring)
- VAL(string)
- STR(number)
26String Functions Example
- CLS
- LET me "Joseph A. Komar "
- LET you "Komar "
- LET first LEFT(me, 6)
- LET last RIGHT(me, 6)
- LET middle MID(me, 8, 1)
- LET upper UCASE(me)
- LET length LEN(you)
- LET init INSTR(me, you)
- PRINT last, first, middle, upper
- PRINT length, init
- END
27Data Input
- Data is stored in DATA statements
- DATA statements are read with the READ statement
(RESTORE to go back to first DATA statement) - Keyboard input is supplied by way of the INPUT
statement
28Sample DATA Statement
- CLS
- READ name, wage, hrs
- PRINT name wage hrs
- READ name, wage, hrs
- PRINT name wage hrs
- DATA "Joe Komar",10.33,40
- DATA "Susan Komar",15.40,45
- END
29INPUT Statement
- CLS
- INPUT "Enter Name, wage rate, and hours" name,
wage, hrs - LET total wage hrs
- PRINT name " Hourly rate " wage "Total
Wages" total - END
30Advanced PRINT
- PRINT zones -- four of 14 characters, one of 24
characters - TAB(n) -- positions cursor at position n across
screen - LOCATE r,c -- positions cursor at row r and
column c - PRINT USING -- uses picture or format for
numbers
31PRINT USING
- Format string
- ,.
- ,. -- fixed dollar sign
- ,. -- floating dollar sign
- \ \ -- reserves space for
character strings - See Appendix C for additional functionality
32Example ofPRINT USING
- CLS
- PRINT " January February
March " - PRINT
- LET a "\ \ , ,
, " - PRINT USING a "House" 1010 1020 1030
- PRINT USING a "Beer" 210 220 130
- PRINT USING a "Other" 350 2300 220
- END
33Output to PrinterLPRINT
- CLS
- LPRINT " January February
March " - LPRINT
- LET a "\ \ , ,
, " - LPRINT USING a "House" 1010 1020 1030
- LPRINT USING a "Beer" 210 220 130
- LPRINT USING a "Other" 350 2300 220
- END
34Decision Structure
Then
Else
IF
Process 2
Process 1
35Simple IF Statement
- CLS
- INPUT "Enter Revenues " revenue
- INPUT "Enter Costs " costs
- IF revenue gt costs THEN
- PRINT "Revenue is greater than costs"
- ELSE
- PRINT "Costs are greater than or equal to
revenue" - END IF
- PRINT "Profit " revenue - costs
- END
36Nested IFs
- INPUT "Enter Revenue " revenue
- INPUT "Enter Costs " costs
- IF revenue costs THEN
- PRINT "Break even"
- ELSE
- IF costs lt revenue THEN
- PRINT "Profit " revenue - costs
- ELSE
- PRINT "Loss " costs - revenue
- END IF
- END IF
- END
37IF with no ELSE
- CLS
- INPUT "Do you want instructions? (y or n) " ans
- IF ans "y" THEN
- PRINT "Here's more instruction"
- END IF
- PRINT "The next question is..."
- END
38CASE logic (avoiding many nested IFs)
- SELECT CASE selector
- CASE valuelist1
- action1
- CASE valuelist2
- action2
- .
- CASE ELSE
- action if none of the above
- END SELECT
39CASE logic example
- INPUT "Enter Grade (A,B,C,D, or F) " grade
- SELECT CASE grade
- CASE "A"
- points 4
- CASE "B"
- points 3
- CASE "C"
- points 2
- CASE "D"
- points 1
- CASE ELSE
- points 0
- END SELECT
- PRINT "Grade Points are " points
- END
40Logical Connectors
- OR -- either item can be true
- (g lt 4) OR (m gt 7)
- (ans y) OR (ans Y)
- AND -- both items must be true
- (g lt 4) AND (m gt 7)
- NOT -- negative of the condition
- NOT (g lt 4)
41Logical ConnectorsExample
- CLS
- INPUT "Do you want instructions? (y or n) " ans
- IF (ans "y") OR (ans "Y") THEN
- PRINT "Here are the instructions"
- END IF
- PRINT "Here's the next question"
- END
42DO WHILE
NO
True?
YES
Process
43DO WHILE Example
- CLS
- INPUT "Enter the beginning balance " balance
- INPUT "Enter the interest rate " interest
- LET years 0
- DO WHILE balance lt 1000000
- LET balance balance interest balance
- LET years years 1
- LOOP
- PRINT "In" years "years you will have
1,000,000 dollars" - END
44DO UNTIL
Process
YES
True?
NO
45DO UNTIL Example
- CLS
- LET ans Y
- DO UNTIL (ans "n") OR (ans "N")
- INPUT "Enter the beginning balance " balance
- INPUT "Enter the interest rate " interest
- LET years 0
- DO WHILE balance lt 1000000
- LET balance balance interest
balance - LET years years 1
- LOOP
- PRINT "In" years "years you will have
1,000,000 dollars" - INPUT "Do you want to run again? (y or n) "
ans - LOOP
- END
46Looping Considerations
- Watch out for infinite loops (CtrlBreak)
- Nesting of loops is a very common practice
- Remember that the condition on the DO can be
compound
47FOR...NEXT Loops
- Used when you know exactly how many times a loop
should be performed - FOR i m TO n (STEP s)
- inumeric variable
- minitial value
- nterminal value
- sincrement (one if left off)
- End loop with NEXT i
48FOR...NEXT Example
- CLS
- INPUT "Enter beginning population " pop
- INPUT "Enter beginning year " year
- INPUT "Enter rate of growth " rate
- INPUT "Enter the number of years " num
- FOR i year TO year num
- PRINT i,
- PRINT USING "," pop
- LET pop pop rate pop
- NEXT i
- END
49Nesting of Loops
- Nested loops must be totally contained in the
outside loop
50Controlling Program FlowSummary
- IF..THEN...ELSE
- SELECT CASE
- AND, OR, NOT logical connectors
- DO WHILE...LOOP
- DO UNTIL...LOOP
- FOR...NEXT (STEP)
51Arrays
- Same variable names with subscripts
- DIM (m TO n)
- mbeginning item number (usually 1)
- ntotal number of items in the array
- Often used with FOR...NEXT loops
- Essential in processing lists of like things --
e.g. scores of students, names of presidents, etc.
52Array Example
- CLS
- DIM name(1 TO 5)
- DIM score(1 TO 5)
- FOR i 1 TO 5
- INPUT "Enter name, score" name(i), score(i)
- NEXT i
53Array Example (contd)
- LET high score(1)
- LET who name(1)
- LET which 1
- FOR i 2 TO 5
- IF score(i) gt high THEN
- high score(i)
- who name(i)
- which i
- END IF
- NEXT i
- PRINT "Student " which " scored " high "
name " who - END
54Arrays, more generalized
- CLS
- INPUT "Enter the number of students" num
- DIM name(1 TO num)
- DIM score(1 TO num)
- FOR i 1 TO num
- INPUT "Enter name, score" name(i), score(i)
- NEXT i
55Arrays, more generalized (contd)
- LET high score(1)
- LET who name(1)
- LET which 1
- FOR i 2 TO num
- IF score(i) gt high THEN
- high score(i)
- who name(i)
- which i
- END IF
- NEXT i
- PRINT "Student " which " scored " high "
name " who - END
56Sorting
- Bubble Sort
- Uses the SWAP statement in BASIC
- SWAP var1,var2
- Requires (n-1) passes to completely order the
array (where n is the number of items in the array
57Sorting Example
- CLS
- INPUT "Enter the number of students" num
- DIM name(1 TO num)
- DIM score(1 TO num)
- FOR i 1 TO num
- INPUT "Enter name, score" name(i), score(i)
- NEXT i
58Sorting Example (contd)
- FOR i 1 TO num - 1
- FOR j 1 TO num - i
- IF score(j) lt score(j 1) THEN
- SWAP name(j), name(j 1)
- SWAP score(j), score(j 1)
- END IF
- NEXT j
- NEXT i
59Sorting Example (contd)
- PRINT "Highest to lowest score"
- PRINT
- FOR i 1 TO num
- PRINT score(i), name(i)
- NEXT i
60Sorting -- First output
- Highest to lowest score
- 95 James
- 88 Winsock
- 73 Komar
- 68 Anderson
- 56 Tornado
61Sorting Example (contd)
- FOR i 1 TO num - 1
- FOR j 1 TO num - i
- IF name(j) gt name(j 1) THEN
- SWAP name(j), name(j 1)
- SWAP score(j), score(j 1)
- END IF
- NEXT j
- NEXT i
62Sorting Example (contd)
- PRINT
- PRINT "Alphabetical List"
- PRINT
- FOR i 1 TO num
- PRINT score(i), name(i)
- NEXT i
- END
63Sorting -- Second output
- Alphabetical List
- 68 Anderson
- 95 James
- 73 Komar
- 56 Tornado
- 88 Winsock
64Searching
- Sequential -- used with an unordered array -- see
example of finding the highest score - Binary -- used with a sorted array
- Start in the middle
- Determine which way to go from there
- Can be used in day-to-day searching
65Searching Example
- INPUT "Enter the student to find" find
- LET first 1
- LET last num
- LET found 0
66Searching Example (contd)
- DO WHILE (first lt last) AND (found 0)
- LET middle INT((first last) / 2)
- SELECT CASE name(middle)
- CASE find
- LET found 1
- CASE IS gt find
- LET last middle - 1
- CASE IS lt find
- LET first middle 1
- END SELECT
- LOOP
67Searching Example (contd)
- IF found 1 THEN
- PRINT "Found " find
- ELSE
- PRINT find " not found"
- END IF
- END
68Arrays Summary
- Variable name with a subscript
- name(number)
- DIM (m TO n)
- Bubble sort -- arranges item in array
- Searching
- Sequential with an unordered list
- Binary with an ordered list
69Subprograms
- Performs one or more related tasks
- Written as a separate part of the program
- Accessed via a CALL statement
- SUB subprogramname
- statements
- END SUB
- May pass parameters (arguments)
70Subprogram Example
- CLS
- INPUT "Enter two numbers" first, second
- CALL addem(first, second)
- END
- SUB addem (a, b)
- LET c a b
- PRINT a " " b " " c
- END SUB
71Subprogram Purpose
- Allows for modularity of large programs
- Allows for reusable program code
- Frequently executed code can be isolated
- Code can be changed in one place only
- Subprograms can call other subprograms
72Subprogram to Main Program
- CLS
- INPUT "Enter two numbers" first, second
- CALL addem(first, second, sum)
- PRINT "The sum is " sum
- END
- SUB addem (a, b, c)
- LET c a b
- PRINT a " " b " " c
- END SUB
73Subprogram Results
- Enter two numbers? 12,13
- 12 13 25
- The sum is 25
74Subprogram Argument Passing
- Order of arguments is critical
- Arguments must match in kind -- numeric with
numeric, string with string - Arguments passed can be expressions
- CALL (x5,y15,z)
- Can pass arrays -- e.g., name()
- Variables are local to subprograms
75Main Program and SUBs
- Main program can have three components
- Input Process Output
- SUBs then perform each of these functions
- SUBs can, themselves be main programs
76Sequential File Creation
- Open the file for writing
- OPEN filespec FOR OUTPUT AS n
- Use the WRITE statement to write data into the
file - WRITE n, variablelist
- Close the file when done
- CLOSE n
77File Creation Example
- CLS
- OPEN "Ajunk.dat" FOR OUTPUT AS 1
- WRITE 1, "Komar", 25000
- WRITE 1, "Anderson", 32000
- WRITE 1, "Johnson", 43000
- CLOSE 1
- END
78File Creation Example
- "Komar",25000
- "Anderson",32000
- "Johnson",43000
79Appending to a File
- Open the file for appending
- OPEN filespec FOR APPEND AS n
- Write to the file
- WRITE n, variablelist
- Close the file when done
- CLOSE n
80Reading a File
- Open the file for reading
- OPEN filespec FOR INPUT AS n
- Read data from the file
- INPUT n, variablelist
- Use the EOF(n) function to detect end-of-file
- Close the file when done
- CLOSE n
81Reading Example
- CLS
- OPEN "Ajunk.dat" FOR INPUT AS 1
- DO WHILE NOT EOF(1)
- INPUT 1, name, salary
- PRINT name, " makes ", salary
- LOOP
- END
82Reading example
- Komar makes 25000
- Anderson makes 32000
- Johnson makes 43000