# Basic Programming

Document Sample

```					                   Basic Programming

Joe Komar

Komar Associates                       1
Computer Programs

Input         Processing      Output

Komar Associates                                2
Programming Tools

 Flowcharts

 Pseudocode

 Top-down      Charts

Komar Associates                       3
Flowcharts

Flowline

Input/Output

Terminal
Decision
(start/end)

Processing

Komar Associates                                4
Flowcharts
Start

Data

Process
Data

Print
Result

Komar Associates    End          5
Pseudocode

 English    like description of program
steps:
Read number of items and cost
Multiply cost times number
Display the number of items, cost,
and total

Komar Associates                                 6
Top-Down Chart
Program Name

Data               Data       Results

Komar Associates                               7
Programming Structures

   Sequential -- One step after another

   Decision Structure -- IF...Then...Else

   Looping Structure -- DO WHILE (or DO

UNTIL)

Komar Associates                                   8
Sequential Structure

Step 1

Step 2

Step 3

Komar Associates                          9
Decision Structure

Else          Then
IF

Process 2                      Process 1

Komar Associates                                    10
Looping Structure

NO
True?

YES

Process

Komar Associates                       11
Arithmetic Operations

Subtraction               -
Multiplication            *
Division                  /
Exponentiation            ^

Komar Associates                           12
Numbers

 Constants -- e.g. 17, 1.329, 1.4E+3
 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
Komar Associates                                          13
Sample Program

CLS
LET rate = 50
LET time = 14
LET distance = rate * time
PRINT distance
LET distance = 410
LET time = distance / rate
PRINT time
END
Komar Associates                    14
Basic Statements

   CLS -- Clears Screen

   LET -- LET var = expression

   PRINT -- PRINT list (use of ;)

   END -- signifies end of program
Komar Associates                            15
Qbasic

 Type QBASIC at DOS prompt
File Edit View Search Run Debug Options
   “Smart” editor catches many Syntax
errors
 REM is for remarks, such as your name
and date

Komar Associates                                     16
Programming Exercise
Create and run the following program:

CLS
PRINT gpa
END

Change values for grades and run again.
Komar Associates                                       17
Relational Operators

= equal to
<> not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

Komar Associates                                  18
Functions

 Prewritten routines that “return” a value
based on one or more inputs
 Examples:
SQR(expression)

INT(expression)
Expression is a number, variable, or
calculation

Komar Associates                                    19
A Word to the Wise

   Complete as many of the odd number
exercises as you can, checking your

   Get familiar with the “mechanics” of
using the Qbasic editor

Komar Associates                                 20
Strings

 Strings are anything other than numbers
 String constants are enclosed in double
quotes (“)
 String variable names end with a dollar
sign (\$)

Komar Associates                                  21
Example 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

Komar Associates                                           22
Strings

   Concatenation
Use plus sign (+) between strings

   Get all ASCII characters with the character
string function:
CHR\$(number)
(see Appendix A for ASCII chart)

Komar Associates                                        23
String Relationships

= identical to
<> different from
< precedes alphabetically
> follows alphabetically
<= precedes or identical
>= follows or identical
(special characters, digits, upper, lower)
Komar Associates                                   24
String 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)
Komar Associates                                25
String 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
Komar Associates                              26
Data 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

Komar Associates                                     27
Sample DATA Statement

CLS
PRINT name\$; wage * hrs
PRINT name\$; wage * hrs
DATA "Joe Komar",10.33,40
DATA "Susan Komar",15.40,45
END

Komar Associates                           28
INPUT 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

Komar Associates                                                   29

 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
Komar Associates                                    30
PRINT USING

   Format string
“##,###.##”
“\$##,###.##” -- fixed dollar sign
“\$\$#,###.##” -- floating dollar sign
“\      \” -- reserves space for
character strings
   See Appendix C for additional
functionality
Komar Associates                                  31
Example of
PRINT 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

Komar Associates                                    32
Output to Printer
LPRINT
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

Komar Associates                                      33
Decision Structure

Else          Then
IF

Process 2                      Process 1

Komar Associates                                    34
Simple IF Statement
CLS
INPUT "Enter Revenues: "; revenue
INPUT "Enter Costs: "; costs
IF revenue > 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

Komar Associates                                                35
Nested IFs
INPUT "Enter Revenue: "; revenue
INPUT "Enter Costs: "; costs
IF revenue = costs THEN
PRINT "Break even"
ELSE
IF costs < revenue THEN
PRINT "Profit = "; revenue - costs
ELSE
PRINT "Loss = "; costs - revenue
END IF
END IF
END
Komar Associates                               36
IF 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

Komar Associates                                          37
CASE logic (avoiding many
nested IFs)

SELECT CASE selector
CASE valuelist1
action1
CASE valuelist2
action2
.
CASE ELSE
action if none of the above
END SELECT
Komar Associates                         38
CASE logic example
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
Komar Associates                                      39
Logical Connectors

   OR -- either item can be true
(g < 4) OR (m > 7)
(ans\$ = “y”) OR (ans\$ = “Y”)
   AND -- both items must be true
(g < 4) AND (m > 7)
   NOT -- negative of the condition
NOT (g < 4)

Komar Associates                                  40
Logical Connectors
Example

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

Komar Associates                                          41
DO WHILE

NO
True?

YES

Process

Komar Associates                   42
DO WHILE Example
CLS
INPUT "Enter the beginning balance: "; balance
INPUT "Enter the interest rate: "; interest
LET years = 0
DO WHILE balance < 1000000
LET balance = balance + interest * balance
LET years = years + 1
LOOP
PRINT "In"; years; "years you will have \$1,000,000 dollars"
END

Komar Associates                                                    43
DO UNTIL

Process

YES
True?

NO

Komar Associates                    44
DO 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 < 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
Komar Associates                                                     45
Looping Considerations

 Watch out for infinite loops (Ctrl+Break)
 Nesting of loops is a very common
practice
 Remember that the condition on the DO
can be compound

Komar Associates                                    46
FOR...NEXT Loops

   Used when you know exactly how many times a
loop should be performed
   FOR i = m TO n (STEP s)
i=numeric variable
m=initial value
n=terminal value
s=increment (one if left off)
   End loop with NEXT i

Komar Associates                                        47
FOR...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

Komar Associates                                  48
Nesting of Loops

Nested loops must be totally contained in the
outside loop:

Komar Associates                                      49
Controlling Program Flow
Summary

   IF..THEN...ELSE
   SELECT CASE
   AND, OR, NOT logical connectors
   DO WHILE...LOOP
   DO UNTIL...LOOP
   FOR...NEXT (STEP)

Komar Associates                            50
Arrays

   Same variable names with “subscripts”
   DIM (m TO n)
m=beginning item number (usually 1)
n=total 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.

Komar Associates                                               51
Array 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

Komar Associates                                          52
Array Example (cont’d)
LET high = score(1)
LET who\$ = name\$(1)
LET which = 1
FOR i = 2 TO 5
IF score(i) > high THEN
high = score(i)
who\$ = name\$(i)
which = i
END IF
NEXT i
PRINT "Student # "; which; " scored "; high; " name: "; who\$
END
Komar Associates                                                     53
Arrays, 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

Komar Associates                                        54
Arrays, more generalized
(cont’d)
LET high = score(1)
LET who\$ = name\$(1)
LET which = 1
FOR i = 2 TO num
IF score(i) > high THEN
high = score(i)
who\$ = name\$(i)
which = i
END IF
NEXT i
PRINT "Student # "; which; " scored "; high; " name: "; who\$
END
Komar Associates                                                     55
Sorting

   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

Komar Associates                                             56
Sorting 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

Komar Associates                                        57
Sorting Example (cont’d)

FOR i = 1 TO num - 1
FOR j = 1 TO num - i
IF score(j) < score(j + 1) THEN
SWAP name\$(j), name\$(j + 1)
SWAP score(j), score(j + 1)
END IF
NEXT j
NEXT i

Komar Associates                              58
Sorting Example (cont’d)

PRINT "Highest to lowest score"
PRINT
FOR i = 1 TO num
PRINT score(i), name\$(i)
NEXT i

Komar Associates                              59
Sorting -- First output

Highest to lowest score

95          James
88          Winsock
73          Komar
68          Anderson

Komar Associates                             60
Sorting Example (cont’d)

FOR i = 1 TO num - 1
FOR j = 1 TO num - i
IF name\$(j) > name\$(j + 1) THEN
SWAP name\$(j), name\$(j + 1)
SWAP score(j), score(j + 1)
END IF
NEXT j
NEXT i

Komar Associates                              61
Sorting Example (cont’d)

PRINT
PRINT "Alphabetical List"
PRINT
FOR i = 1 TO num
PRINT score(i), name\$(i)
NEXT i
END

Komar Associates                              62
Sorting -- Second output

Alphabetical List

68           Anderson
95           James
73           Komar
88           Winsock

Komar Associates                              63
Searching

 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

Komar Associates                                    64
Searching Example

INPUT "Enter the student to find:"; find\$
LET first = 1
LET last = num
LET found = 0

Komar Associates                                  65
Searching Example (cont’d)
DO WHILE (first <= last) AND (found = 0)
LET middle = INT((first + last) / 2)
SELECT CASE name\$(middle)
CASE find\$
LET found = 1
CASE IS > find\$
LET last = middle - 1
CASE IS < find\$
LET first = middle + 1
END SELECT
LOOP

Komar Associates                                 66
Searching Example (cont’d)

IF found = 1 THEN
PRINT "Found "; find\$
ELSE
END IF
END

Komar Associates                          67
Arrays 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

Komar Associates                                 68
Subprograms

 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)
Komar Associates                             69
Subprogram Example

CLS
INPUT "Enter two numbers:"; first, second
END
LET c = a + b
PRINT a; " + "; b; " = "; c
END SUB

Komar Associates                                  70
Subprogram 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

Komar Associates                                   71
Subprogram to Main Program

CLS
INPUT "Enter two numbers:"; first, second
PRINT "The sum is: "; sum
END
LET c = a + b
PRINT a; " + "; b; " = "; c
END SUB

Komar Associates                                  72
Subprogram Results

Enter two numbers:? 12,13
12 + 13 = 25
The sum is: 25

Komar Associates                        73
Subprogram Argument Passing

 Order of arguments is critical
 Arguments must match in kind --
numeric with numeric, string with string
 Arguments passed can be expressions
CALL (x+5,y*15,z)
 Can pass arrays -- e.g., name\$()
 Variables are local to subprograms

Komar Associates                                   74
Main 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

Komar Associates                           75
Sequential 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

Komar Associates                                  76
File Creation Example

CLS
OPEN "A:junk.dat" FOR OUTPUT AS #1
WRITE #1, "Komar", 25000
WRITE #1, "Anderson", 32000
WRITE #1, "Johnson", 43000
CLOSE #1
END

Komar Associates                           77
File Creation Example

"Komar",25000
"Anderson",32000
"Johnson",43000

Komar Associates                           78
Appending 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

Komar Associates                                  79

   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
Komar Associates                                    80

CLS
OPEN "A:junk.dat" FOR INPUT AS #1
DO WHILE NOT EOF(1)
INPUT #1, name\$, salary
PRINT name\$, " makes ", salary
LOOP
END

Komar Associates                          81

Komar        makes   25000
Anderson     makes   32000
Johnson      makes   43000

Komar Associates                     82

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 5 posted: 9/29/2012 language: Unknown pages: 82
How are you planning on using Docstoc?