Continued On EEE211 (Electrical Engineering Course

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

COMPUTER AND COMPUTING (ENG 201)

INTRODUCTION

The term "computer" refers to an electronic device that is capable of receiving, storing, processing,
and outputting data according to instructions encoded in programs or software. Computers come in
various forms and sizes, from large mainframe systems to small personal devices like laptops,
desktops, tablets, and smartphones.

Computing, on the other hand, is the process of using computers and computational techniques to
perform tasks such as data processing, information retrieval, problem-solving, and communication.
Computing involves not only hardware (the physical components of computers) but also software
(programs and applications), algorithms, data structures, networks, and human-computer interaction.

In essence, computing encompasses the entire ecosystem of activities related to the use and
development of computer systems, including programming, software engineering, computer science,
data analysis, artificial intelligence, and more. It plays a crucial role in virtually every aspect of
modern life, from business and education to entertainment and scientific research.

WHY TO WE NEED PROGRAMMING LANGUAGES?


Programming languages are essential tools for communicating instructions to computers in a way that
humans can understand. Here's a brief overview of why programming languages are necessary and their
historical context:
1. Machine Language: In the early days of computing, programmers had to write instructions
directly in machine language, which is a binary code consisting of 0s and 1s that the computer's
CPU could understand. This was incredibly tedious and error-prone, as it required a deep
understanding of the computer's architecture and was not easily readable or writable by humans.
2. Assembly Language: As a step forward, assembly language was developed, which used
mnemonic codes to represent machine instructions, making programming somewhat more
readable and manageable. However, it was still closely tied to the computer's architecture and
required significant effort to write and debug.
3. High-Level Programming Languages: The need for more user-friendly programming led to the
development of high-level programming languages like Fortran, COBOL, and Lisp in the late
1950s and early 1960s. These languages allowed programmers to write code using more natural
language constructs and abstracted away many of the low-level details of the underlying
hardware.
4. Increased Abstraction and Productivity: Over time, programming languages continued to
evolve, offering higher levels of abstraction and productivity. Languages like C, developed in the
1970s, provided a balance between low-level control and high-level abstraction, making them
popular for system programming and application development.
5. Diverse Ecosystem: Today, there is a vast ecosystem of programming languages catering to
different domains and requirements. From general-purpose languages like Python, Java, and C++
to domain-specific languages for web development, data science, and artificial intelligence,
programmers have a wide range of tools at their disposal.
6. Ease of Maintenance and Collaboration: Programming languages also facilitate code
maintenance and collaboration. With well-designed syntax and standardized conventions,
programmers can easily understand, modify, and extend each other's code, enabling teamwork
and code reuse.
In summary, programming languages are necessary to bridge the gap between human understanding and
machine execution, enabling efficient and scalable software development across various domains. Their
evolution has been driven by the need for improved productivity, abstraction, readability, and
maintainability in software development.

Program Life Cycle


The following are six steps in the Program Development Life Cycle (PDLC):
1. Analyze the problem. The computer user must figure out the problem, then decide how to resolve
the problem - choose a program.
2. Design the program. A flow chart is important to use during this step of the PDLC. This is a visual
diagram of the flow containing the program. This step will help you break down the problem
3. Code the program. This is using the language of programming to write the lines of code. The code
is called the listing or the source code. The computer user will run an object code for this step.
4. Debug the program. The computer user must debug. This is the process of finding the "bugs" on
the computer. The bugs are important to find because this is known as errors in a program.
5. Formalize the solution. One must run the program to make sure there are no syntax and logic errors.
Syntax are grammatical errors and logic errors are incorrect results.
6. Document and maintain the program. This step is the final step of gathering everything together.
Internal documentation is involved in this step because it explains the reasoning one might of made
a change in the program or how to write a program
A program is a series of instructions that the computer executes in order to perform some meaningful
work. For example, the developers at Microsoft created a program called Word that performs word
processing activities for a user.
Programming is the process of creating a set of instructions that tell a computer how to perform a
task. Programming can be done using a variety of computer "languages," such Java, Python, C, and
C++, etc.
Program design is the process of converting a set of requirements into a collection of commands or a
program that can be executed on a computer system. Program design is an integral part of software
development and depending on the methodology used, can be a significant step in the process.
The objective of program design is directed towards the following goals.
1. Reliability: the program can be depended upon always to do what is supposed to do.
2. Maintainability: the program will be easy to change or modified when the need arises
3. Readability: the program will be easy for programmer to read and understands
4. Portability: The program will be transferable to different computer with minor or modifications
required.
5. Performance: The program will cause task to be done quickly and efficiently.
6. Storage saving: The will be no too much unnecessary codes in the program.

Pseudocode and Flowcharts


Software development is complex and usually involves many parties working together. Therefore, planning
out a project before beginning to program is essential for success.

Good, logical programming is developed through good pre-code planning and organization. This is assisted
by the use of pseudocode and program flowcharts.

Pseudocode is a detailed yet readable description of what a computer program or algorithm should do. It
is a methodology that allows the programmer to represent the implementation of an algorithm.
Pseudocode is not a programming language and cannot be compiled into an executable program. Instead,
it serves as a blueprint for translating the code’s logic into an actual programming language.
Rules for writing Pseudocode
• The usual Fortran symobols are used for arithmetic operations (+, -, *, / , **).
• Symbolic names are used to indicate the quantities being processed.
• Certain Fortran keywords can be used, such as PRINT, WRITE, READ, etc.
• Indentation should be used to indicate branches and loops of instruction.
Example
Pseudocode:
Input: Two Integers
Ouput: Sum of Two Integer
1. Create first number variable
2. Create second number variable
3. Create Sum variable
4. Receive First number from the user
5. Receive second number from the user
6. Add First to Second number and store it in the Sum variable
7. Print Sum
Implementation of the above Pseudocode Using C++ is as follows:
#include<iostream>
using namespace std;
int main(){
// Adding two numbers
int first_number, second_number, sum;
//get the first number
cout<<"Pls enter First number"<<endl;
cin>>first_number;
//get second number
cout<<"Pls enter second number"<<endl;
cin>> second_number;
// Add two numbers and store the result in sum
sum = first_number + second_number;
//print sum
cout<<"The sum of firt_number and Second number is: " << sum<<endl;
}
Flowchart
A flowchart is a picture of the separate steps of a process in sequential order. It is a generic tool that
can be adapted for a wide variety of purposes and can be used to describe various processes, such as a
manufacturing process, an administrative or service process, or a project plan. Shapes make it easier to
solve problems.
A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as
a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. The flowchart
shows the steps as boxes of various kinds and their order by connecting the boxes with arrows. This
diagrammatic representation illustrates a solution model for a given problem. Flowcharts are used in
analyzing, designing, documenting, or managing a process or program in various fields.

The following shapes are often used in flowcharts:

Example:
What Is an Engineering Flowchart?
Definition
An engineering flowchart is a visual demonstration of the steps in a real-world design project of an engine,
machines, building, roads, and other engineered objects.
Benefits of using flowcharts:
1. It can deliver the right image of the company:
If you are working for a corporation, then you must draw diagrams to present on any project. Always
remember one thing: the clients and other businesses are always attracted to companies who provide them
a clear and productive brief of their services. Flowchart can be extremely effective when presenting project.
So, utilize this option to close more business deals.
2. It can increase productivity:
Well-designed and well-managed flowchart can impress your client, and your company gets benefits from
it. The company will get more clients and business as the people will know the professionalism of the
company.
3. It will be easy to understand the process:
If you explain the process or any idea with a lot of arguments, it is possible that many of the people don’t
understand it. Still, if you use the flowchart and utilize it in a practical way, then everybody will understand
your processes correctly.
4. It can make your life easy:
The main aim of introducing the flowchart is to make every process understandable and accessible. It’s not
only better for your understanding but for others’ as well. Even if you have kids at home, you can draw the
flowchart for their projects too so they can take more interest in their studies.
Here are some of the ways flowcharts are used today.
• Project planning
• Program or system design through flowchart programming
• Process documentation
• Audit a process for inefficiencies or malfunctions
• Map computer algorithms
• Documenting workflow
INTRODUCTION TO QBASIC
The name QBasic is an acronym for Quick Beginners All Purpose Symbolic Instruction Code. It was
developed and launched by Microsoft in the year 1991 and is considered to be one of the most ideal
languages for absolute beginners.
QBASIC. QBASIC is a programming language. With a programming language you can tell the computer
what you want it to do. It's a lot like giving someone directions to your house. The computer follows each
step and does exactly what you tell it. By programming the computer, you can solve math problems, create
art or music, and even make new games. It's all up to you.
BASIC ELEMENT OF QBASIC
Every programming language consists of some basic elements which are required to make a program. The
element required to construct a QBASIC program consists of a set of characters (Symbol), Identifiers,
variables, Datatype, Statements, flow control, Arrays, Function, keywords, constants, operators and
expressions.
1. CHARACTER SET
A set of characters that are allowed to use in QBASIC is known as the QBASIC Character Set. The character
set includes the alphabet, numbers and special characters. Special symbols, sign other than alphabets, and
numbers are called special characters.
QBASIC CHARACTER SET CATEGORIES

• Alphabet: A to Z or a to z
• Numerical/digits: 0 to 9
• Special characters: $,%,@,!,(,_,),?, \, / etc..
2. IDENTIFIER
Name used for a variable or constant.
3. VARIABLE
A variable is a place in the computer memory which has a name and stores data temporarily. Simply, you
can say, a variable is an entity that stores data needed to be used in a program. Each program defines
different number of variables. A value of a variable can be change during the execution of the program.
There are mainly two types of variables. They are:
i. String Variable
ii. Numeric Variable
A string variable stores sting data. Its types declaration sign is dollar ($). A numeric variable stores numeric
data. A numeric variable can be Integer, Long Integer, Single Precision or Double Precision variables.
An Integer variable can store only an integer number. Its type declaration sign is percentage (%).
A Long integer variable can store a large range of whole number. Its type declaration sign is ampersand
(&0).
A Single Precision variable can store a whole number as well as number with decimal. Its type declaration
sign is exclamation sign (!). You can also use it without declaration sign. It is the default numeric variable.
A Double Precision variable also stores a whole number as well as number with decimal point. Its type
declaration sign is hash (#).
Rules for naming a variable
a. Variable names can have maximum of 40 characters.
b. Variable names can have alphabets, numbers and decimal point.
c. A Variable name must begin with a letter.
d. A Variable name cannot begin with fn or FN alphabets. For example, fnames$, fnumetc.
e. Variable names cannot be reserved words.
f. Variable names may be ended with type declaration characters like $, %, &, !, and #.
Naam$, Address$, Bookname$, GameName$, etc., are examples of String Varibales.
Salary!, Age%, Mark, Number1, Number2, FirstNum, RollNumber, etc., are examples of Numeric
Variables.
Declaration of Variables

In a most programming languages, variables must be declared in advance for the compiler. One of the
most popular features of BASIC was that it didn’t force the programmer to declare all variables in
advance.

What is Declaration and Initialization?

• Declaration of a variable in a computer programming language is a statement used to specify the


variable name and its data type. Declaration tells the program about the existence of an entity in
the program and its location.
• Initialization is the process of assigning a value to the Variable. If the value is not assigned to the
Variable, then the process is only called a Declaration.

In QBASIC variable can be declared in the following two ways:

Implicit Declaration:

In an implicit variable declaration, the type of variable is declared at the same time when the value is
assigned to it. The variable type is declared by using data type declaration characters which are always
used as suffixes in the variable names such as ($,%,! and #).

Example: a%=45678

Example: m$= “Dhangadhi”


Explicit Declaration:

A variable declaration that can be declared before they are used in a program without any data type suffix
is known as the explicit declaration. it is generally done at the beginning of the program. A variable is
declared explicitly using a DIM statement. This type of declaration does not assign the value but informs
the program about variables.

Syntax:

DIM variable name AS TYPE

Variable: Any valid variable names

Type: defines the types of variables (numeric and string) it can be INTEGER, LONG, SINGLE
DOUBLE, STRING

Example:

DIM marks AS INTEGER

Here, Marks is declared as an integer variable explicitly

DIM name AS STRING

Here, the name is declared as a string variable explicitly.

OPERATOR

Operators are symbols that indicate the type of operation QBASIC has to perform on the data or on the
values of variables. There are four types of operators in QBASIC. They are Arithmetic Operators,
Relational Operators, Logical Operators and String Operator.

a. Arithmetic Operators

Arithmetic Operators are used to perform mathematical calculations like addition, subtraction, division,
multiplication and exponential. The following table shows arithmetic operators used in QBASIC.

Operation Operator Example Result

i. Addition + 5+8 13

ii. Subtraction - 8-6 2

iii. Multiplication * 5*4 20

iv. Division / 8/2 4

v. Integer Division \ 9\2 4

vi. Exponential ^ 4^3 64


vii. Modular Division Mod 7 mod 3 1

b. Relational Operators

Relational Operators are used to perform comparisons on two values of same type. A comparison of
string data with numeric data cannot be done. The result of comparison is either true (non - zero) or false
(zero).

The following table shows the relational operators used in QBASIC.

Operator ------------- Relation ------------------------------- Example

i. = --------------------- Equal to -------------------------------- A = B, A$ = B$

ii. > -------------------- Greater than --------------------------- A > B, “CAT”>”RAT”

iii. < ------------------- Less than ------------------------------- A < B, "cat" < "cat"

iv. > = ---------------- Greater than or equal to ---------------- A > = B, X$ > = Y$

v. < = ----------------- Less than or equal to ------------------- A < = B, X$ < = Y$

vi. < > ---------------- Not equal ------------------------------ A$ < > B$, X <> Y.

c. Logical Operators

Logical Operators combine two or more relational expressions to evaluate a single value as True (Non
Zero) or False (Zero). The result of evaluation is used to make decisions about the program flow. The
commonly used logical operators in QBASIC are AND, OR and NOT.

i. AND Operator:

AND operator returns ‘True’ when all the results returned from individual relational expressions are
‘True’ otherwise it returns ‘False’.

The AND Truth Table is given shown below.

Condition1 (P) ------------- Condition2 (Q) -------------- Result (P AND Q)

F ------------------------------- T ----------------------------------- F

T ------------------------------- F ----------------------------------- F

F ------------------------------- F ----------------------------------- F
T ------------------------------- T ----------------------------------- T

Note: A ‘T’ indicates a true value and a ‘F’ indicates a false value.

ii. OR Operator:

OR Operator return ‘True’ if any one of the relational expressions returns ‘True’. If all the relational
expressions returns ‘False’ then only the combined result returned by OR operator will be ‘False’.

The OR Truth table is as given below.

Condition 1 (A) ------------------ Condition2 (Q) --------------- Result (A or B)

F ------------------------------------------- T ---------------------------------- T

T ------------------------------------------- F ---------------------------------- T

T ------------------------------------------- T ---------------------------------- T

F -------------------------------------------- F ---------------------------------- F

iii. NOT Operator:

NOT Operator operates on one operand and returns ‘True’ if the logical operation returns ‘False’. The
NOT truth table is as given below.

Condition1 (A) --------------------------- Result (NOT A)

F ----------------------------------------------- T

T ----------------------------------------------- F

d. String Operator

String Operator joins two or more than two sting data. The plus sign (+) is used as the String operator.
The act of combining two stings is called concatenation. The following table shows the use of Sting
Operator.

String Data (A$) -------------------- Sting data (B$) ----------------- A$ + B$


“Ram” ---------------------------------- “Thapa” ------------------------ Ram Thapa

“50” ------------------------------------- “45” ----------------------------- 5045

EXPRESSIONS

An expression is the combination of operators, constants and variables that is evaluated to get a result.
The result of the expression is either string data, numeric data or logical value (true or false) and can be
stored in a variable. For example, the following are expressions in QBASIC.

(A + B) > C

A>=B+C

u* t + ½*a*t^2

An arithmetic expression may contain more than one operator. While evaluating such expressions, a
hierarchy is followed. The hierarchy in arithmetic operations is listed as given below:

a. Exponentiation (^)

b. Negation (-)

c. Multiplication and division

d. Integer division

e. Modular division

f. Addition and Subtraction

The hierarchy in relational operations are =, >, <, <>, < =, and > = respectively. The hierarchy in logical
operations are NOT, AND and OR.

NOTE:

When parenthesis is used, it changes the order of hierarchy. The operators inside the parenthesis are
evaluated first. So, you can say QBASIC expression follows rule of PEDMAS where P, E, D, M, A and S
stand for parenthesis, Exponentiation, Division, Multiplication, Addition, and Subtraction respectively.

Algebraic expression cannot be used directly in programming. It must be converted into QBASIC
expression.

Algebraic Expression ------------------------- BASIC Expression

A = L × B ------------------------------------------------- A = L * B
P = 2(L + B) ---------------------------------------------- P = 2*(L + B)

I = (P × T × R)/100 --------------------------------------- I = (P * T * R)/100

V = 4/3 pi R^3 ------------------------------------------- V = 4/3 * PI * R^3

DATATPE
Information such as name, age, date, salary, marks, etc. is called data. Datatype is a classification identifying
one of various types of data, as floating-point, integer, or Boolean, stating the possible values for that type,
the operations that can be done on that type, and the way the values of that type are stored. Such data types
used in QBASIC are given by:
a) String Data Types
i) Variable Length String
ii) Fixed Length String
b) Numeric Data Types
i) Integer
ii) Long integer
iii) Single Precision
iv) Double Precision
a) String Data Types
A string is a combination of characters and they are real objects, and hence, it is possible to concatenate,
modify and test them.
The string data type is a combination of alphanumeric characters which are enclosed by double quotation
marks and assigned to a string variable. The data range of the string variable is 0 to 32767 characters and
memory consumption is 4 bytes. There are two types of string data types. They are given below:
i) Variable length string
Any text or alphanumeric value which can be input from or enclosed by a double quotation mark is called
a variable length string.
Example:
LET N$ = “Class 9”
INPUT “Enter your name: “ ; N$
DIM Nam AS STRING
In the given example N$ is a variable length variable which do not have any fixed character length and can
be declared or used wherever we need in the program. The variable N$ may store any string value with a
different length. Such variable declaration is called an implicit declaration.
ii) Fixed length string
A fixed length string is also a text or alphanumeric value whose length is specified by the corresponding
variable.
Example:
DIM Nam AS STRING * 15
DIM Address AS STRING * 30
In the given example Name and Address are the fixed length string variable. The variable Name and
Address can store only 15 and 30 characters respectively. Fixed length string variable must declare before
use with specified number of characters’ length. In case of fewer characters, it keeps blank spaces to
consume a given number of characters.
b. Numeric Data Types
Numeric data types are any numeric values either positive or negative. There are four different types of
numeric data types in QBASIC. They are given below:
i) Integer
The integer data type is a positive or negative number that does not contain a decimal point. Or the number
without a decimal point is called integer data type.
Integer variable name used % sign with the name of the variable. The range for integer variables is from -
32768 to 32767 and memory consumption 2 bytes.
Example: age% = 15
ii) Long integer
The integer data type has a very short range so that long integer data type is used to store such large numbers.
Long integer data is stored to the variable which is used & sign with the name. Its range is from -
2147483648 to 2147483647 and its memory consumption 4 bytes.
Example:
n& = 123454321
iii) Single Precision:
A single precision variable can store floating point numbers up to six digits after the decimal point. If the
number contains 7 digits, it is rounded to the closed value. The single precision variable is declared using
the exclamation (!) symbol at the end of the variable name. It occupies 4 bytes of storage space in the
memory.
Example:
per!, interest! etc.
iv) Double Precision:
The double precision variable holds numbers having decimal point up to 16 digits. It is declared using the
hash (#) symbol at the end of the variable name. It stores numeric data occupying 8 bytes of memory space.
Example:
total#, gross# etc.
5. STATEMENT
Qbasic Statements is a command or set of instructions used in the program. The statement performs specific
task in the program. A statement will have internal components (e.g., expressions).
6. Flow control
Flow control statements altered the way a program is executed. E.g IF and ELSE.
7 Array
An array is a single programming variable with multiple “compartments”. Each compartment can hold a
value.
8 Function or Subroutine
A subroutine or subprogram (also called procedure, method, function, or routine) is a portion of code within
a larger program, which performs a specific task and is relatively independent of the remaining code.
9 Constant
A special kind of variable whose value cannot typically be altered by the program during its execution.

FLOW CONTROL
Program flow refers to the order in which a program's instructions are executed. The flow of the program
is controlled by loops, conditionals, and function calls, which dictate the sequence of instructions that are
executed by the program.
Flow control are the methods for changing, controlling the flow by which instructions are ‘executed’ or
‘processed’ by the computer.
Types of flow control
1. Linear flow control
When program instructions are processed one after the other is a straight sequence, this flow is called
“linear”. In our flow-chart symbols, we can see this by the arrows always flowing straight down
without any deviations.
2. Branching
When a program execution changes direction for only a specified condition, this is called branching.
We can see this in our flow-chart symbols when certain instructions may possibly be ignored, or when
certain instructions may only be accessed for a given condition. Whenever a change in instruction flow
is diagrammed it is always shown as a diamond shape, indicating that the program makes a decision
at that point for which side it will branch to.

Branches are designed to allow certain instructions to be used, while ignoring others. Branches can
also be used to ignore certain instructions if the conditions are not right for using them.

Types of branching flow control


i. IF…THEN
ii. IF…THEN…ELSE
iii. IF THEN…ELSE IF
iv. SELECT CASE
v. GOTO
THE IF…THEN STATEMENT
This is the decision making statement that decide which statement has to be executed on the basis of
specified condition.
Syntax for IF…THEN:

IF condition THEN
statement(s)
END IF

The condition is the expression that is to be evaluated. If the condition is true, then the statements inside
the IF THEN block are executed. If the condition is false, then the statements are skipped.

For example, the following code checks if a variable x is greater than 10 and prints a message if it is:

Example 1: check whether x is greater than 10


x = 15
IF x > 10 THEN
PRINT "x is greater than 10"
END IF

In this case, since x is greater than 10, the message "x is greater than

Example 2: check a number, variable numb% whether it is a positive number or not and draw its
equivalent flow chart.

SOLUTION:

IF numb% > 0 THEN


PRINT “This number is a positive number”
END IF

Example 2:
CASE STUDY: CHECKING THE SALES RESULTS FROM THE SHOP
Our faculty shop sometimes makes money, sometimes it does not make as much money as we want. We
would like a computer program that will compare the daily sales to the shop goal sales. We can set up a
target, and ask for the sales. When the sales meet or exceeds the target then we are happy, but when the
sales are below the target this is not a good thing. Also draw the equivalent flow chart of the program

SOLUTION
performance$ = "We are not happy"
INPUT "Trget "; target
INPUT "hop Sales "; shopSales
IF shopales >= target THEN
perfomance$ = "We are Happy"
ENDIF
REM printing the final result
PRNT “*===========================*” PRINT "Target "; target
PINT "Sales "; shopSales
RINT "Performance "; performance$
THE IF…THEN…ELSE STATEMENT

In QBASIC, the IF...THEN...ELSE statement is used to perform conditional programming, where there
are two possible outcomes based on the evaluation of a condition.

The basic structure or syntax of the IF...THEN...ELSE statement is as follows:

IF condition THEN
statement(s) ' executed if the condition is true
ELSE
statement(s) ' executed if the condition is false
END IF

IF…THEN…ELSE STATEMENT FLOW CHART

The condition is the expression that is to be evaluated. If the condition is true, then the statements inside
the first block of the IF...THEN...ELSE statement are executed. If the condition is false, then the
statements inside the ELSE block are executed.

For example, the following code checks if a variable x is greater than 10. If it is, then it prints a message
saying so. Otherwise, it prints a message saying that x is not greater than 10.
x=5
IF x > 10 THEN
PRINT "x is greater than 10"
ELSE
PRINT "x is not greater than 10"
END IF

In this case, since x is not greater than 10, the message "x is not greater than 10" will be printed.

Example 2:

CASE STUDY. PROVIDING A BONUS WHEN SALES ARE HIGH

To give our shop staff incentives to try and increase sales we decided that we will give them a bonus if
the sales is higher than the target. When sales exceeds or meets the target we want to give a bonus, but
when the sales are below the target we want to not give a bonus.

SOLUTIONS

INPUT "Target "; target


INPUT "shopSales "; shopSales
IF canteenSales >= target THEN
performance$ = “We are Happy”
bonus = 100 + 0.01 * shopSales - target)
ELSE
performance$ = “We are NOT Happy”
bonus = 0
ENDIF
PRINT “*===========================*”
PRINT "Target "; target
PRINT "Sales "; shopSales
PRINT "Performance "; performance$
PRINT "Bonus "; bonus
IF

THEN Performance$=”we’re
Sales>=target
happy”

bonus=bonusValue
ELSE

Performance$=”we’re
not happy”

bonus = 0

THE IF…THEN…ELSE IF
It’s multi-way decision making statement that is use when there are two or more decisions to be
evaluated.

Syntax:
IF condition1 THEN
[statementblock-1]
[ELSEIF condition2 THEN
[statementblock-2]]...
[ELSE
[statementblock-n]]
END IF
Flow chart

IF

ELSEIF
Condition
1!
THEN

Condition
Statement(s)
THEN ELSEIF

Example 1: Statement(s) Condition N


CLS THEN
INPUT "Enter a number between 1 and 100: ", num
IF num < 0 THEN
Statement(s)
PRINT "The number must be greater than 0."
ELSEIF num <= 50 THEN
PRINT "The number is between 1 and 50."
ELSEIF num <= 100 THEN
PRINT "The number is between 51 and 100."
ELSE
PRINT "The number is greater than 100."
END IF

SELECT CASE
The SELECT statement uses the value of testexpression to transfer control to one of the CASE statements
for execution. The expressionlist is a list of values which is compared to the testexpression to determine
which CASE statement is executed. When the testexpression does not match any of the expressionlists,
then the CASE ELSE statement is executed.
Syntax:
SELECT CASE testexpression
CASE expressionlist1
[statementblock-1]
[CASE expressionlist2
[statementblock-2]]...
[CASE ELSE
[statementblock-n]]
END SELECT

Example 1: grade computation

REM Program to input score and compute grade


REM using SELECT CASE... END SELECT structure
CLS
DIM Score AS INTEGER, Grade AS STRING
INPUT "Please Enter Student's Score Here: ", Score
SELECT CASE (Score)
CASE 70 TO 100
Grade = "A"
CASE 60 TO 69
Grade = "B"
CASE 50 TO 59
Grade = "C"
CASE 40 TO 49
Grade = "D"
CASE ELSE
Grade = “F”
END SELECT
PRINT
PRINT "The Student's Score Is: "; Score
PRINT
PRINT "The Student's Grade Is: "; Grade
END

Example 2: Day Selection program


CLS
INPUT "Date Number "; dayNumber
SELECT CASE dayNumber
CASE 1
PRINT "Monday"
CASE 2
PRINT "Tuesday"
CASE 3
PRINT "Wednesday"
CASE 4
PRINT "Thursday"
CASE 5
PRINT "Friday"
CASE 6
PRINT "Saturday"
CASE 7
PRINT "Sunday"
CASE ELSE
PRINT "How many days in your Week?"
END SELECTEND

You might also like