0% found this document useful (0 votes)
2 views

Programming Notes-1

Chapter 8 covers fundamental programming concepts including variables, constants, data types, input/output operations, arithmetic operators, control structures (sequence, selection, iteration), and string handling. It explains how to declare and use identifiers, perform arithmetic calculations, and implement logical conditions using IF statements and CASE statements. Additionally, it introduces subroutines, procedures, and functions, emphasizing their importance in code reuse and program efficiency.

Uploaded by

567 899
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming Notes-1

Chapter 8 covers fundamental programming concepts including variables, constants, data types, input/output operations, arithmetic operators, control structures (sequence, selection, iteration), and string handling. It explains how to declare and use identifiers, perform arithmetic calculations, and implement logical conditions using IF statements and CASE statements. Additionally, it introduces subroutines, procedures, and functions, emphasizing their importance in code reuse and program efficiency.

Uploaded by

567 899
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter 8: Programming

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

2. Understand and use the basic data types


 Data type defines the type of data that will be stored in a variable
 There are five types of data types in Programming Language
Data Type Description Example data
Integer Holds Whole number 1
23
-300
45656
Real, single, Holds Decimal numbers 1.2
double 23.0
-20.49
3949.3834
Char Holds One character or number of symbol. “h”
The data will always need to be inside speech “9”
marks, either ‘ ‘ or “ “ “?”
String Holds Text, character, number and symbols. “hello”
The data will always need to be inside speech “123”
marks, either ‘ ‘ or “ “ “help!”
Boolean Either true or false TRUE
FALSE

3. Understand and use input and output


Output
A data that is displayed to the user usually on-screen
Example1: output (“Hello world”)
Example2: output (20)

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

Example1: Input number

Example2: input “Enter the value:”, number


Or
Output “Enter the value”
Input number

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

Example1: Taking two numbers as input and performing arithmetic operations


Output (“Enter the first number”)
Input num1
Output (“Enter the second number”)
Input num2
add = num1 + num2
sub = num1 – num2
mul = num1 * num2
div = num1 / num2
res1 = MOD (33, 7)
res2 = DIV (33, 7)

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

Logical Operator Description Example


= or = = Equals to 10 = 10 ? would give TRUE
10 = 2 ? would give FALSE
< > or ! = Not equal to 10 < > 10? Would give FALSE
10 <> 2? Would give TRUE
< Less than 10 < 11? Would give TRUE
10 < 10 would give FALSE
11 < 10 would give FALSE
<= Less than or equal to 10 <= 11? Would give TRUE.
10 <= 10? Would give TRUE
11 <=10? Would give FASLSE
> Greater than 10 > 11? Would give FALSE
10 > 10 would give FALSE
11 > 10 would give TRUE
>= Greater than or equal to 10 > = 11? Would give FALSE
10 > = 10 would give TRUE
11 > = 10 would give TRUE

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.

Example1: Age based access


Input age
If age < 10 Then
Output “You are not old enough”
Elseif age < 14 then
Output “You need an adult present”
Elseif age < 20 then
Output “You are eligible”
Else
Output “Pls Retype your age”
Endif
End

SELECT CASE statements


A SELECT CASE statement allows the program to take one variable or value, and then have lots of different options
depending what it is equal to
Example1:
Input “Enter score=”, score
Select case score
Case 90 to 100: output (“A*”)
Case is > = 80: Output (“A”)
Case is > = 70: output (“B”)
Case is > = 60: output (“C”)
Case is > = 50: output (“D”)
Case else
output (“U”)
End case

Boolean Description Example


Operator
AND If both conditions are IF 1 =1 AND 2 = 2
true, the result is true. This will return TRUE. The left of the AND is true,
If one or both and the right of the AND is true.
conditions are false, IF 1 = 1 AND 1 > 2
the result is false This will return FALSE. The left of AND is true, but
the right of AND is false.
IF 1 < -2 AND 0 < -1
This will return FALSE. Both comparisons are false,
so the result is false.
OR If one, or both, IF 1 =1 OR 2 = 2
conditions are true, This will return TRUE. The left of the OR is true, and
the result is true. the right of the OR is true.
If both conditions are IF 1 = 1 OR 1 > 2
false, the result is false This will return TRUE. The left of OR is true, but the
right of OR is false.
IF 1 < -2 OR 0 < -1

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.

Post condition loop


A post-condition loop runs the code inside the loop once, and then checks the condition at the end of the loop. This
means that the code will always run once.
A REPEAT UNTIL loop is a post-condition loop.

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

The first character of the string can be position zero or one

1. Output how many characters in the given string - length


Cls
Output LENGTH(“Hello”)
End

Output
5

2. a) Output the string from the start


Cls
Output SUBSTRING(“Hello”, 1,1)
End

Output
H

b) Output the first three letters


Cls
Output SUBSTRING(“Hello”, 1, 3)
End

Output
Hel

b) Output the string from the middle


Cls
Output SUBSTRING(“Hello”, 3, 3)
End

Output
llo

3. Output how many characters are in the entered word


Dim na as String
Cls
Input "Enter your name:", na
Output LENGTH(na)
End

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

5. Output the string one character at a time in reverse


Dim word as string
Dim count as integer
Cls
Input “Enter your text”, word
For count=LENGTH(word) to 1 step -1
Output SUBSTRING(word, count, 1)
Next count

Output
O
L
L
E
H

6. Changing the text into Uppercase


Cls
Output UPPER (“Hello)
End

Output
HELLO

7. Changing the text into Lowercase


Cls
Output LOWER (“Hello”)
End

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 and Functions


Subroutines
A subroutine is a self-identified piece of code that has an identifier (name), and it can be called from anywhere in the
main program
Subroutines are useful because they reduce code. You write the subroutine once, and then you can call it as many times
as you need to.
There are two ways of subroutine: procedure and functions. A function returns a value to the program that called it. A
procedure does not return a value.
Procedures and functions can both take one or more values as parameter. These are values that are sent to the
subroutine.
● Procedures and functions is a sub program not the main or whole program
● It is a set of programming instructions for a given task
● Used to perform frequently used operation within a program
● Subroutine can be called when needed
● It can be reused by another program
● Sub-routines written in high-level programming languages are called ‘procedures’ or ‘functions’ depending on
how they are used.

Why Procedures and Functions are needed


 To allow procedures and Functions to be re-used within the program
 To make program creation faster
 To make program shorter
 To enable the programmer to write program statements under a single identifier

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

Example program1: Outputing Stars


Cls
Call stars
End

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

Example Program3: Adding two numbers using a procedure


Dim num1, num2, add as integer
Call addsum

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

PROCEDURE add(a,b) //a,b are global variables whereas c is a local variable


c = a+b
Output “Addition of two numbers=”, c
End PROCEDURE

PROCEDURE subt(a,b) //a,b are global variables whereas c is a local variable


c=a-b
Output “Subtraction of two numbers=”, c
End PROCEDURE

PROCEDURE mult(x, y) //x,y are global variables whereas c is a local variable


c = x*y //a, b values are assigned to x, y variables
Output “Multiplication of two numbers=”, c
End PROCEDURE

PROCEDURE div(m, n) //m,n are global variables whereas c is a local variable


c=m/n //a, b values are assigned to m, n variables
Output “Division of two numbers=”, c
End PROCEDURE

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: Adding Two numbers using Function with parameters


cls
Input “Enter number1:”, num1
Input “Enter number2:”, num2
Output addnums(num1, num2)
End

FUNCTION addnums(num1, 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 areaofrect(length, breadth)


areaofrect=length*breadth
end FUNCTION

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

c) Using Procedures and Functions


allow you to write a block of code once and reuse it multiple times in a program. This prevents code duplication and
saves time when writing or modifying the program. Both procedures and functions break down a large program into
smaller, manageable sections. Each section performs a specific task, making the program easier to understand, develop,
and test.

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.

One dimensional arrays


Definition: an array that has only one index
Index: the number of the space in the array
One dimensional array has just one row of data.
The best way to visualise an array is with a table:
Index 0 1 2 3 4
Data 10 5 90 26 87

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

Benefits of storing data in a file


 data is stored permanently
 data can be moved to another computer
 another copy of data can be made and stored, accessed anywhere and can be used as a back up copy

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)

Example 3: Write the word "red" to the file colour. txt:


OPEN "colour.txt"
WRITE "red"
CLOSE "colour.txt"

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

You might also like