Programming Notes-1
Programming Notes-1
Programming Concepts
1. Declare and use variables and constants
Variable: a named memory location that can store data. The data can change whilst a program is running
Example1:
Number = 10
Colour = “red”
Price = 22.2
Output (Number)
Output (“The colour is “, colour)
Output (“The price of the product=”, price)
Constant: a named memory location that can store data. The data cannot change whilst a program is running. Before
you use a constant in your program you need to give it a value. This is an assignment statement as same as a variable.
Example1:
Const Colour = “Yellow”
Const value = 10
Identifier: a name given to a variable, constant, data structure (e.g. array) or subroutine.
Example1: Number = 10
Here number is identifier, 10 is a value
Example2: output (number)
Output is a command; number is an identifier. To get data out of a variable you just use its identifier
1|Page
Concatenation: joining two or more strings together
Example:
name = Azim
Output (“Hello”, name)
Input
The user entering data into the program, usually from a keyboard
Arithmetic Operators
Arithmetic operators instruct a program to perform calculations.
Operator Description Example
+ Adds two values together 10 + 2 gives 12
- Subtracts the second value from the first 11.3 – 9 gives 2.3
* Multiplies two values together 10 * 2 gives 20
/ Divides the first number by the second 11.3 / 9 gives 1.256
DIV Give the whole number after the first number is Div (10, 2) gives 5
divided by the second, i.e. it ignores any decimals
MOD Gives the remainder after the first number is divided MOD (10, 2) gives 0
by the second, i.e. how many are left
^ Power of 2^3=8
Sequence
A sequence is a series of statements that are executed once, in the order they are written
Output (“Enter a colour”)
Input colour
Output (“Enter your name”)
Input name
Output (Name, “Your favourite colour is”, colour)
2|Page
Selection
In selection a condition is checked and this determines which, if any, code is run. There are two forms of selection,
IF statements and CASE statements
Conditions need logical operators. These allow for comparisons to be made. Each statement using a logical
operator results in TRUE or FALSE
IF Statements
The command IF is followed by a condition that is created using the logical operators. There are three stages of IF
statements; IF, ELSE and ELSEIF
IF has one comparison and the code inside the IF will only run if that condition is True. If it is not true, the code in the IF
statement will not run
Example1:
num1 = 15
num2 = 7
If num1 > num2 then
Output “Num1 is bigger”
Endif
Else Statements
This is added within an IF statement. If the IF statement’s condition is false, then the ELSE will run. You can only ever
have one ELSE in an IF statement
Example1:
num1 = 15
num2 = 7
If num1 < num2 then
Output “Num1 is bigger”
Else
Output “num2 is bigger”
Endif
3|Page
ElseIF statement
This allows for a second condition to be used within the same IF statement. If the first condition is False, then a
second condition can be checked.
4|Page
This will return FALSE. Both comparisons are false,
so the result is false.
NOT Reverse the condition, IF NOT (1 = 1)
if the condition is True The brackets equal to TRUE, 1 equals 1. The NOT
it becomes false makes if FALSE, so it becomes 1 does not equal 1.
IF NOT (End of File)
This is used with file handling. End of File will return
TRUE if there is no data left in the file. The NOT
turns this to false. So while not at the end of the file.
Example1: This will output the first message if both test marks are greater than or equal to 90. If only one mark is
greater than or equal to 90 then the second message will output.
Output (“Enter the mark for test1”)
Input mark1
Output (“Enter the mark for test2”)
Input mark2
If mark1 >= 90 AND mark2 >= 90 then
Output (“Well done you got top marks on both tests”)
ELSEIF mark1 >=90 OR mark2 >=90 THEN
Output (“Well done you got top marks on one of the tests”)
ELSE
Output (“You didn’t quite get top marks on the test, try again next time”)
ENDIF
Example2: Output the highest number out of three that are input:
Output (Enter 3 numbers”)
Input number1
Input number2
Input number3
IF number1 > number2 AND number1 > number3 then
Output (number1)
Elseif number2 > number3 then
Output (number2)
Else
Output (number3)
Endif
5|Page
Iteration
An iteration or loop is a programming construct where statements are run either a finite number of times, until a
condition is true or while a condition is true.
count-controlled loop
This type of loop uses a counter to run a set number of times. The most count-controlled loop is the for loop.
Example1. Enter five numbers and output the total and average of given numbers using looping structure
dim num, count as integer
dim sum as integer
cls
sum=0
for count=1 to 5
input “enter the number:”;num
sum=sum+num
next count
output “The total of given 5 numbers=”sum
End
Pre-condition loop
A pre-condition loop tests the condition before starting the loop. This means that if the condition is false, the code
inside the loop will not run. It loops while the condition is true. It stops looping when the condition is false
A WHILE loop is a pre-condition loop.
Example1. Enter five numbers and output the total and average using “while” loop
dim num as integer
dim sum as integer
cls
sum=0
count=1
while count<=5
input “enter the number:”num
sum =sum + num
count=count+1
wend
output “The total of given 5 numbers=”, sum
End.
6|Page
Example1. Enter five numbers and output the total and average using “while” loop
dim num as integer
dim sum as integer
cls
sum=0
count = 1
do/repeat
input “enter the number:”num
sum =sum + num
count=count+1
loop until count>5 / count=4 / num=-1
output “The total of given 5 numbers=”, sum
End
Totalling
Totalling is adding together a set of values. To wirte a program to total you need to,
Initialise the total to 0
Add the values together
Total = 0
For count = 1 to 10
Input num
Total = total + num
Next count
Output “The total is “, total
Counting
Counting is working out how many of something there are. For example how many numbers were entered that were
over 10. To write a program to count you need to,
Initialise a counter variable to 0
Increment the counter each time as item is entered
abovefifty = 0
For count = 1 to 10
Input num
If num > 50 then
Abovefifty = abovefifty + 1
end
Next count
Output “The numbers above fifty are “, abovefifty
7|Page
String Handling
e) Understand and use the concept of string handling
length
substring
upper
lower
Output
5
Output
H
Output
Hel
Output
llo
Output
Enter your name: Hello world
11
8|Page
4. Output the string one character at a time
Dim word as string
Dim count as integer
Cls
Input “Enter your text”, word
For count=1 to LENGTH(word)
Output SUBSTRING(word, count, 1)
Next count
Output
H
E
L
L
O
Output
O
L
L
E
H
Output
HELLO
Output
hello
9|Page
Assignment:
1. Display how many letters in the given string of “Hi Welcome!” by using an algorithm
2. Display “come” from the typed word of “welcome” by using an algorithm
3. Display the entered text in reverse order
4. Change the input text “WELCOME” input into lower case
Procedures
● Procedure is a sub program
● Procedure is defined one time and can be called many times
● Values can be passed through parameters
● Can be used by specific calls in the program
● it does not return a value
● Used to perform calculations
Sub stars
Output "****"
End Sub
10 | P a g e
Example program2: Outputing Stars using parameters
Dim i as integer
Cls
Call stars(i)
End
Sub stars(i)
for i = 1 to 5
Output "****"
next i
End Sub
PROCEDURE addsum
Input “Enter number1:”, num1
Input “Enter number2:”, num2
add=num1+num2
Output “Addition=”, add
End PROCEDURE
Parameters
A parameter is a value that is sent from the main program to the subroutine (Procedure or Function). Parameters are
declared inside the brackets after the subroutines name.
Example Program4: Adding two numbers using a procedure, Passing values through a parameter
Dim num1, num2, add as integer
Cls
Input “Enter number1:”, num1
Input “Enter number2:”, num2
Call addsum(num1, num2) //Passing values num1, num2 through parameter to Procedure
End
PROCEDURE addsum(num1, num2) //num1, num2 are global variables, can be accessed from any part of the program
add=num1+num2 //add is a local variable, can be accessed only in the subroutine
Output “Addition=”, add
End PROCEDURE
11 | P a g e
Example5: Performing arithmetic calculations using a procedure, passing values through a parameter
Cls
Input a
Input b
Call add(a,b)
Call subt(a,b)
Call mult(a,b)
Call div(a,b)
End
Class Work:
Enter inputs to find and display area of square
Enter inputs to find and display area of rectangle
Use procedure for the given tasks above, Use parameters to pass variables
Functions
● Function is a subprogram
● Function is defined one time and can be called many times
● Values can be passed through parameters
● Can be used by specific calls in the program
● it always returns a value
● Used for calculations
12 | P a g e
Example Program1: Adding Two numbers using Function
Cls
Result = addnums
Print “The addition=”, Result
End
FUNCTION addnums
Input num1
Input num2
addnums = num1 + num2
End FUNCTION
Example Program2: Finding Area of Square and Area of Rectangle by calling two different functions, Area(len),
rectangle(len, breadth)
cls
input “Enter length=”,length
input “Enter breadth=”,breadth
output areaofrect(length, breadth)
output areaofsquare(length)
end
FUNCTION areaofsquare(length)
Areaofsquare=length * length
End FUNCTION
Scope
The scope is the sections in the code where the variable, or constant, can be accessed. There are two scopes: global and
local
Global scope: is the variable or constant can be accessed from any part of the program
Value can be changed anywhere in the program
Local scope: is the variable or constant can only be accessed in the subroutine it is declared within.
Value cannot be changed elsewhere in the program
13 | P a g e
Library routines
A program library is a set of subroutines that are pre-written and that can be called within a program
Examples: DIV, MOD, ROUND, RANDOM
DIV is used to perform integer division, DIV (15,2) = 7
MOD is used to find the remainder in division of two numbers. MOD (15,2) = 1
ROUND(10.123,1) will return a round value of specified number of digits, like 10.1
RoundedValue = ROUND(77.486, 2), the output is RoundedValue = 77.48
Example:
Input “Enter a number: ”, num
roundedNum = ROUND(num, 2)
RANDOM – This will generate a random number between two values that it takes as parameters.
Example: RANDOM(10,20) will return a number between 10 and 20
randomNumber = RANDOM(1, 100) //RANDOM function is assigned to a variable
Example:
For i = 1 to 5
randomNum = RANDOM(10, 20)
Output “Random Number “, i , “: “, randomNum
Next i
Maintainable programs
This means a program that has key features to help it be understood at a later date. The given ways below help in
maintain a program
a) Meaningful Identifiers
Variables, constants, subroutines and arrays all have identifiers (names). If you call a variable X, then there is no
indication of what it is storing or what its purpose is. If instead, it is called Total, then you know that it is storing a total.
The identifiers for subroutines are usually descriptions of their function. For example, a procedure to output the
numbers 1 to 10 could be called Function1, but then there is no indication of what it does, instead, it could be called
Output1To10
b) Comments
Comment is a description of a line of code, it is not executed when the program is run
Example:
FOR count = 0 to 9 //Input 10 numbers
INPUT num
Sum = sum + num //Adding input numbers to calculate the total of all 10 numbers
NEXT count
14 | P a g e
Array
An array is a data structure. It allows you store multiple pieces of data in one structure with one identifier. In an array,
each data item must be of the same data type. It stores integers, then all values must be integer. If it stores strings, then
all values must be strings.
This array has 5 spaces. Each space has an index. In this array the first data item is in position 0, the data value is 10. In
the second array space (index 1), the number 5 is stored.
Arrays can be 0-indexed or 1-indexed. Arrays use brackets after the identifier to indicate the index you want to access.
For example, Namearray[0] is accessing the first element in the array named NameArray. NameArray[3] is accessing the
fourth element in the array named NameArray.Example: Enter and store 10 numbers in an array and displaying
them
dim num(10) as integer Enter numbers: 101 Number[1]=101
dim i,j as integer Enter numbers: 102 Number [2]=102
cls Enter numbers: 103 Number [3]=103
For i= 1 to 10 Enter numbers: 104 Number [4]=104
Input “Enter numbers:’, num(i) Enter numbers: 105 Number [5]=105
next i Enter numbers: 106 Number [6]=106
for j=1 to 10 Enter numbers: 107 Number [7]=107
print “Number[“, j ,”]=”, num(j) Enter numbers: 108 Number [8]=108
next j Enter numbers: 109 Number [9]=109
Two dimensional arrays Enter numbers: 110 Number [10]=110
Definition: an array that has two indices
Index: the number of the space in the array
Two dimensional array has multiple columns and rows
Two dimensional array is best viewed as a table with rows and columns
Index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
In a 2-dimensional array there are two indices. For example, from the table:
Position [0,0] is 10
Position [0,2] is 7
Position [4,2] is 24
15 | P a g e
Example: Entering and displaying numbers into 2d array Enter the value: 5
Dim myarray (3, 3) As Integer Enter the value: 8
Cls Enter the value: 6
Enter the value: 7
For col = 1 To 3
Enter the value: 9
For row = 1 To 3 Enter the value: 45
Input "Enter the value:", myarray(col,row) Enter the value: 87
Next row Enter the value: 41
Next col Enter the value: 2
5
For col = 1 To 3
8
For row = 1 To 3 6
Print myarray(col,row) 7
Next row 9
Next col 45
87
End
41
2
File Handling
If you have data in a program, then you stop or close a program all of that data is lost. If you need to save data to use
again later then you need to save it externally into a text file. The storage and access of data in a file is called file
handling
File handling: programming statements that allow text files to be opened, read from, written to and closed.
Example1: Reading and outputting a word stored in the text file data. txt:
OPEN "data.txt"
OUTPUT (READ ("data. txt"))
CLOSE "data.txt"
Example 2: Read and output the number stored in the file myNumber. txt by storing the filename in a variable: Filename
= "myNumber.txt"
OPEN Filename
TheFileData = READ(Filename)
CLOSE(Filename)
OUTPUT(TheFileData)
16 | P a g e
Example 4: Write the number 100 to the file myData.txt storing the filename in a variable:
Filename = "myData.txt"
OPEN Filename
WRITE 100
CLOSE Filename
QBasic Programs
Example1: create a text file and store data into it.
Open “demo.txt" For Output As #1
Input "Enter the name:", n$
Input "Enter index num:", in
Input "Enter age:", a
Write #1, n$, in, a
Close #1
Example2: Open the existing file and write more data into it
Open "demo.txt" For Append As #1
Input "Enter the contact num:", cno
Input "Enter the country name:", c$
Write #1, cno, c$
Close #1
17 | P a g e