Professional Documents
Culture Documents
INSTRUCTIONAL MATERIALS
IN
CMPE 20022
COMPUTER PROGRAMMING
Approved by:
Welcome to the Polytechnic University of the Philippines. This instructional materials will help you
become an effective learner and successfully meet the requirements of the course. You will
discover that you can learn in a very challenging way at your own pace. You can learn while
enjoying every activities in this course.
Happy learning!
VISION
MISSION
Ensuring inclusive and equitable quality education and promoting lifelong learning
opportunities through a re-engineered polytechnic university by committing to:
continuously develop faculty and employees with the highest level of professionalism
engage public and private institutions and other stakeholders for the attainment of social
development goal
PHILOSOPHY
Education is an instrument for the development of the citizenry and for the enhancement
of nation building; and
That meaningful growth and transmission of the country are best achieved in an
atmosphere of brotherhood, peace, freedom, justice and nationalist-oriented education
imbued with the spirit of humanist internationalism.
i
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
TEN PILLARS
ii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
MARAGONDON BRANCH
GOALS
PROGRAM OBJECTIVES
6. Continuously conduct action researches on the needs of laboratory and other facilities
that could be locally produce or innovated using local materials and adapted technology
iii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
CMPE 20022
COMPUTER PROGRAMMING
COURSE DESCRIPTION
This course introduces the students to the fundamentals of logic formulation and allows the
student to learn and apply the art and style of procedural programming to solve computational
problems adhering to the standards and guidelines of documentation. It includes discussion on
I/O statements, loop and branching instructions, and creating functions and procedures.
COURSE OBJECTIVES
Design, implement, test and debug a program, based on a given specification that uses such of
the following fundamental programming components: (1) primitive data types (2) basic
computation (3) simple I/O (4) conditional and iterative structures (5) definition of functions and
parameter
Assess and recommend revisions to another programmer’s code (1) regarding documentation
and program style standards that contribute to readability and maintainability of software, (2)
regarding appropriateness of chosen conditional and iterative constructs given a programming
task, and (3) regarding thoroughness in applying procedural abstraction.
iv
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Engagement industry, GO’s and NGO’s, local and and practice voluntarism to contribute in
international which could serve as: community and human development.
7. Adeptness in the a. funding sources and/or partners of Develop software applications and
Responsible researches; management information system applicable to
Use of b. sources of new techniques business environment.
Technology c. centers for faculty and student exchange
8. High Level of program and On the Job Training, and; Exercise empowered leadership and teamwork
Leadership and d. grantees of scholarship/additional facilities in solving computer problems.
Organizational
Skills
9. Sense of Continuously conduct action researches on the Observe the code of ethics and diligence in
Personal and needs of laboratory and other facilities that practicing the profession.
Professional could be locally produce or innovated using
Ethics local materials and adapted technology
COURSE REQUIREMENTS
1. Students are encouraged to attend the class sessions (online students) and complete all
the requirements (online and offline students).
2. The course is expected to have a minimum of four (4) quizzes and two (2) major
examination (Midterm and Final Examination).
3. Other requirements such as written/programming outputs, exercises, assignments and
the likes will be given throughout the sessions. These shall be submitted on the due dates
set by the teacher.
GRADING SYSTEM
The grading system will determine if the student passed or failed the course. There will be two
grading periods: Midterm and Final Period. Each period has components of: 70% Class Standing
+ 30% Major Examination. Final Grade will be the average of the two periodical grades.
Midterm Finals
Class Standing 70% Class Standing 70%
Quizzes Quizzes
Activities Activities
Asignments Project
Mid-term Examination 30% Assignments
Final Examination 30%
FINAL GRADE = (Midterm + Finals) /2
RUBRICS:
Outstanding Very Good Average Poor
5.0-4.5 4.0-3.0 2.5-1.5 1.0
Completeness Complete in all aspects Complete in some Incomplete in many Incomplete and does not
and includes all aspects and includes aspects and includes few include requirements
requirements most of the requirements requirements
Analysis and Use Presents an insightful Presents an insightful Presents shallow Presents incomplete
of the and in-depth analysis of and analysis of most of analysis of data; and analysis of data; and fails
v
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Entrepreneurial all data; uses many the data; uses some uses limited to use entrepreneurial
Concepts and entrepreneurial concepts entrepreneurial concepts entrepreneurial concepts concepts and business
Business Tools and business tools and business tools and business tools tools learned in the
learned in the subject learned in the subject learned in the subject subject
Setting of Presents complete, Presents specific, Presents some Presents limited,
Recommendation realistic, and applicable realistic, and applicable applicable unrealistic
for future action recommendations from, recommendations from recommendations from recommendation from
plans and shows how to use it the data gathered, and the data gathered, and the data gathered, and
in their future action shows how to use it in shows how to use it in failed to show how to use
plans their future action plans. their future action plans. it in their future action
plans.
Over-all The paper has The paper has clarity, The paper lacks clarity, The paper is not clear
cohesiveness sophisticated clarity, conciseness, and conciseness, and and contains serious
(writing and conciseness, and correctness. Includes correctness. Includes errors. Failed to include
presentation) correctness. Includes all some needed relevant limited relevant data and relevant data and
needed relevant data data and analysis. analysis. analysis.
and analysis.
COURSE GUIDE
REFERENCES
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
vii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
TABLE OF CONTENTS
Topic Page
Introduction
Orientation
viii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Lesson 1 - Programming Concepts
Overview:
Let us begin with the word ‘compute’. It means ‘to calculate’. We all are familiar with calculations
in our day to day life. We apply mathematical operations like addition, subtraction, multiplication,
etc. and many other formulae for calculations. Simpler calculations take less time. But complex
calculations take much longer time. Another factor is accuracy in calculations. So man explored
with the idea to develop a machine which can perform this type of arithmetic calculation faster
and with full accuracy. This gave birth to a device or machine called ‘computer’.
Learning Objectives:
1. define a computer
2. identify characteristics of computer
Course Materials:
BASIC CONCEPTS
WHAT IS A COMPUTER?
Therefore, we may define computer as a device that transforms data. Data can be anything like
marks obtained by you in various subjects. It can also be name, age, sex, weight, height, etc. of
all the students in your class or income, savings, investments, etc., of a country. Computer can
be defined in terms of its functions. It can i) accept data ii) store data, iii) process data as desired,
and iv) retrieve the stored data as and when required and v) print the result in desired format.
You will know more about these functions as you go through the later lessons.
1
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
CHARACTERISTICS OF COMPUTER
Let us identify the major characteristics of computer. These can be discussed under the headings
of speed, accuracy, diligence, versatility and memory.
Speed
As you know computer can work very fast. It takes only few seconds for calculations that we take
hours to complete. Suppose you are asked to calculate the average monthly income of one
thousand persons in your neighborhood. For this you have to add income from all sources for all
persons on a day to day basis and find out the average for each one of them. How long will it
take for you to do this? One day, two days or one week? Do you know your small computer can
finish this work in few seconds? The weather forecasting that you see every day on TV is the
results of compilation and analysis of huge amount of data on temperature, humidity, pressure,
etc. of various places on computers. It takes few minutes for the computer to process this huge
amount of data and give the result.
You will be surprised to know that computer can perform millions (1,000,000) of instructions and
even more per second. Therefore, we determine the speed of computer in terms of microsecond
(10-6 part of a second) or nano-second (10-9 part of a second). From this you can imagine how
fast your computer performs work.
Accuracy
Suppose some one calculates faster but commits a lot of errors in computing. Such result is
useless. There is another aspect. Suppose you want to divide 15 by 7. You may work out up to 2
decimal places and say the dividend is 2.14. I may calculate up to 4 decimal places and say that
the result is 2.1428. Some one else may go up to 9 decimal places and say the result is
2.142857143. Hence, in addition to speed, the computer should have accuracy or correctness in
computing.
The degree of accuracy of computer is very high and every calculation is performed with the
same accuracy. The accuracy level is determined on the basis of design of computer. The errors
in computer are due to human and inaccurate data.
Diligence
A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for hours without
creating any error. If millions of calculations are to be performed, a computer will perform every
calculation with the same accuracy. Due to this capability it overpowers human being in routine
type of work.
Versatility
It means the capacity to perform completely different type of work. You may use your computer
to prepare payroll slips. Next moment you may use it for inventory management or to prepare
electric bills.
2
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Power of Remembering
Computer has the power of storing any amount of information or data. Any information can be
stored and recalled as long as you require it, for any numbers of years. It depends entirely upon
you how much data you want to store in a computer and when to lose or retrieve these data.
No IQ
Computer is a dumb machine and it cannot do any work without instruction from the user. It
performs the instructions at tremendous speed and with accuracy. It is you to decide what you
want to do and in what sequence. So a computer cannot take its own decision as you can.
No Feeling
It does not have feelings or emotion, taste, knowledge and experience. Thus it does not get tired
even after long hours of work. It does not distinguish between users.
Storage Capability
The Computer has an in-built memory where it can store a large amount of data. You can also
store data in secondary storage devices such as floppies, which can be kept outside your
computer and can be carried to other computers.
Before getting into computer programming, let us first understand computer programs and what
they do.
A computer program is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.
The two important terms that we have used in the above definition are −
Sequence of instructions
Computer Programming Language
To understand these terms, consider a situation when someone asks you about how to go to a
nearby KFC. What exactly do you do to tell him the way to go to KFC?
You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one
kilometer and you will find KFC at the right.
Here, you have used English Language to give several steps to be taken to reach KFC. If they
are followed in the following sequence, then you will reach KFC −
1.Go straight
2.Drive half kilometer
3.Take left
4.Drive around one kilometer
5.Search for KFC at your right side
Now, try to map the situation with a computer program. The above sequence of instructions is
actually a Human Program written in English Language, which instructs on how to reach KFC
from a given starting point. This same sequence could have been given in Spanish, Hindi,
3
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Arabic, or any other human language, provided the person seeking direction knows any of these
languages.
Now, let's go back and try to understand a computer program, which is a sequence of
instructions written in a Computer Language to perform a specified task by the computer.
Following is a simple program written in Python programming Language −
print "Hello, World!"
The above computer program instructs the computer to print "Hello, World!" on the computer
screen.
A computer program is also called a computer software, which can range from two lines
to millions of lines of instructions.
Computer program instructions are also called program source code and computer
programming is also called program coding.
A computer without a computer program is just a dump box; it is programs that make
computers active.
As we have developed so many languages to communicate among ourselves, computer
scientists have developed several computer-programming languages to provide instructions to
the computer (i.e., to write computer programs). We will see several computer programming
languages in the subsequent chapters.
If you understood what a computer program is, then we will say: the act of writing computer
programs is called computer programming.
As we mentioned earlier, there are hundreds of programming languages, which can be used to
write computer programs and following are a few of them −
Java
C
C++
Python
PHP
Perl
Ruby
Today computer programs are being used in almost every field, household, agriculture, medical,
entertainment, defense, communication, etc. Listed below are a few applications of computer
programs −
MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples of
computer programs.
Computer programs are being used to develop graphics and special effects in movie
making.
Computer programs are being used to perform Ultrasounds, X-Rays, and other medical
examinations.
Computer programs are being used in our mobile phones for SMS, Chat, and voice
communication.
4
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Computer Programmer
Someone who can write computer programs or in other words, someone who can do computer
programming is called a Computer Programmer.
Based on computer programming language expertise, we can name a computer programmers
as follows −
C Programmer
C++ Programmer
Java Programmer
Python Programmer
PHP Programmer
Perl Programmer
Ruby Programmer
Algorithm
The above algorithm has been written in a crude way to help beginners understand the concept.
You will come across more standardized ways of writing computer algorithms as you move on to
advanced levels of computer programming.
5
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Similar to Human Interface Languages, Computer Programming Languages are also made of
several elements. We will take you through the basics of those elements and make you
comfortable to use them in various programming languages. These basic elements include −
Programming Environment
Basic Syntax
Data Types
Variables
Keywords
Basic Operators
Decision Making
Loops
Numbers
Characters
Arrays
Strings
Functions
File I/O
We will explain all these elements in subsequent chapters with examples using different
programming languages. First, we will try to understand the meaning of all these terms in
general and then, we will see how these terms can be used in different programming languages.
This tutorial has been designed to give you an idea about the following most popular
programming languages −
C Programming
Java Programming
Python Programming
A major part of the tutorial has been explained by taking C as programming language and then
we have shown how similar concepts work in Java and Python. So after completion of this
tutorial, you will be quite familiar with these popular programming languages.
6
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
which will be used to write computer programs, compile, and execute them. For example, if you
need to browse Internet, then you need the following setup on your machine −
If you are a PC user, then you will recognize the following screenshot, which we have taken
from the Internet Explorer while browsing tutorialspoint.com.
Similarly, you will need the following setup to start with programming using any programming
language.
In case you don’t have sufficient exposure to computers, you will not be able to set up either of
these software. So, we suggest you take the help from any technical person around you to set
up the programming environment on your machine from where you can start. But for you, it is
important to understand what these items are.
Text Editor
A text editor is a software that is used to write computer programs. Your Windows machine must
have a Notepad, which can be used to type programs. You can launch it by following these
steps −
Start Icon → All Programs → Accessories → Notepad → Mouse Click on Notepad
It will launch Notepad with the following window −
7
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
You can use this software to type your computer program and save it in a file at any location.
You can download and install other good editors like Notepad++, which is freely available.
If you are a Mac user, then you will have TextEdit or you can install some other commercial
editor like BBEdit to start with.
Compiler
You write your computer program using your favorite programming language and save it in a
text file called the program file.
Now let us try to get a little more detail on how the computer understands a program written by
you using a programming language. Actually, the computer cannot understand your program
directly given in the text format, so we need to convert this program in a binary format, which
can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler and
this process of conversion from text formatted program to binary format file is called program
compilation. Finally, you can execute binary file to perform the programmed task.
We are not going into the details of a compiler and the different phases of compilation.
The following flow diagram gives an illustration of the process −
8
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
So, if you are going to write your program in any such language, which needs compilation like C,
C++, Java and Pascal, etc., then you will need to install their compilers before you start
programming.
Interpreter
We just discussed about compilers and the compilation process. Compilers are required in case
you are going to write your program in a programming language that needs to be compiled into
binary format before its execution.
There are other programming languages such as Python, PHP, and Perl, which do not need any
compilation into binary format, rather an interpreter can be used to read such programs line by
line and execute them directly without any further conversion.
9
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need
to install their interpreters before you start programming.
Online Compilation
If you are not able to set up any editor, compiler, or interpreter on your machine,
then tutorialspoint.com provides a facility to compile and run almost all the programs online with
an ease of a single click.
So do not worry and let's proceed further to have a thrilling experience to become a computer
programmer in simple and easy steps.
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
Unit 2 - Flowcharting
Overview:
The flowchart is a means of visually presenting the flow of data through an information
processing systems, the operations performed within the system and the sequence in which they
are performed. In this lesson, we shall concern ourselves with the program flowchart, which
describes what operations (and in what sequence) are required to solve a given problem. The
10
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
program flowchart can be likened to the blueprint of a building. As we know a designer draws a
blueprint before starting construction on a building. Similarly, a programmer prefers to draw a
flowchart prior to writing a computer program. As in the case of the drawing of a blueprint, the
flowchart is drawn according to defined rules and using standard flowchart symbols prescribed by
the American National Standard Institute, Inc.
Learning Objectives:
Course Materials:
MEANING OF A FLOWCHART
A flowchart is a diagrammatic representation that illustrates the sequence of operations to be
performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of
formulating computer solutions. Flowcharts facilitate communication between programmers and
business people. These flowcharts play a vital role in the programming of a problem and are
quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart
is drawn, it becomes easy to write the program in any high level language. Often we see how
flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a
flowchart is a must for the better documentation of a complex program.
11
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Connector or joining of two parts of program
Magnetic Tape
Magnetic Disk
Off-page connector
Flow line
Annotation
Display
(d) Only one flow line should come out from a process symbol.
or
(e) Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, should leave the decision symbol.
No =0
(f) Only one flow line is used in conjunction with terminal symbol.
12
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(g) Write within standard symbols briefly. As necessary, you can use the annotation symbol
to describe data or computational steps more clearly.
(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(h) Ensure that the flowchart has a logical start and finish.
(i) It is useful to test the validity of the flowchart by passing through it with a simple test
data.
SUM = 0
N=0
N=N+1
SUM = SUM + N
IS PRINT SUM
NO YES
N=50?
Fig 2.2 Flowchart for computing the sum of first 50 natural numbers.
Example 2
Draw a flowchart to find the largest of three numbers A,B, and C.
Answer: The required flowchart is shown in Fig 25.3
START
READ A, B, C
14
I I I
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
S S S
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
B A A
C B C
? ? ?
NO NO
END
Fig 25.3 Flowchart for finding out the largest of three numbers
Example 3
Draw a flowchart for computing factorial N (N!)
Where N! = 1 2 3 …… N .
The required flowchart has been shown in fig 25.4
Answer:
START
READ N
M=1
F=1
F=F*M
NO
15
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Note:
S = Salesman number
P1 = Amount of sales of paste
P2 = Amount of sales of powder
K = Counter for the number of salesman
they occur.
(ii) A program flowchart is generally read from _____________ to ________________
17
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(iv) A decision symbol may be used in determining the ____________ or ___________ of two
data items.
(v) __________ are used to join remote portions of a flowchart
(vi) ____________ connectors are used when a flowchart ends on one page and begins again
on other page
(vii) A ________ symbol in used at the beginning and end of a flowchart.
(viii) The flowchart is one of the best ways of ________ a program..
(ix) To construct a flowchart, one must adhere to prescribed symbols provided by the
__________ .
(x) The programmed uses a ____________ to aid him in drawing flowchart symbols.
Do the following:
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
Overview:
18
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
In this lesson, you will be introduced to a programming language called BASIC. It is the most
popular conversational programming language. Various versions of BASIC have been developed
by computer manufacturers for their computers. This language is quite simple to understand and
has been adopted by most of the microcomputers. It is suitable for both mathematical and
business problems. It has been specially designed for use in `time-sharing' environment but can
also be used as a standard language in a `batch-processing' environment.
Learning Objectives:
Course Materials:
Why BASIC?
B in BASIC stands for Beginners. Obviously, it is meant for those who are about to start learning
programming. To qualify as a beginner's language, it has to be simple, easy and readily
available. BASIC has all the qualities. Although, it is the beginner's language, its use by no
means is restricted to basic computer education or elementary applications. The second alphabet
A stands for all-purpose. It means BASIC can be used for a variety of applications involving
business, science, mathematics and graphics. In fact, with new enhancements, BASIC has some
of the powers of more advanced languages. The all purposeness is also derived from the fact
that very large segments of games and computer courseware are written in BASIC. The other
three letters i.e. SIC stand for Symbolic Instruction Code -- means the instructions may not be
exactly in English but expressed in symbols.
19
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
It is available almost in every computer from micro to mainframe. Therefore, a
program developed in a micro can run on bigger system with minor
modifications.
Program development cycle is quick, debugging is simple, and
Modification of programs is quite easy.
History of BASIC
Conceived by John Kemeny and Thomas Kurtz, BASIC was born at Dartmouth College, USA in
1964. It had a rather humble beginning. The classical languages like COBOL or FORTRAN were
already developed. COBOL, in fact, was already established as the major data processing
language. FORTRAN on the other hand, became the principal programming language for
scientific applications. Both these languages, however, were not very simple to learn. There were
extensive rules on syntax and structure of the programs. Because of its simplicity, BASIC gained
immediate popularity. It became a widely used language for small commercial and scientific
applications. BASIC had the same impact on the world of programming languages as the PC had
on the larger computer systems. BASIC's popularity and acceptance by the user community
compelled all the major computer manufacturers to come out with their individual version of
BASIC. When the microcomputer or PCs were introduced, BASIC found a most convenient
vehicle for its proliferation. The ease and simplicity of BASIC made it the standard programming
language for the microcomputer world. Even your MS-DOS operating system comes with a
BASIC interpreter called BASICA. (MS-DOS 3.2 onwards, a more enhanced BASIC version, i.e.,
GWBASIC forms the part of the operating system.) American National Standards Institute (ANSI)
in 1978 came out with a standardised version of BASIC language. Most of the versions of the
currently available BASIC include the features of the ANSI standard.
STRUCTURE OF BASIC
The general structure of standard BASIC language is best understood by a practical program.
The following small program prints the words WELCOME TO NATIONAL OPEN SCHOOL on
the screen:
10 REM: This is my first program
20 PRINT "WELCOME TO NATIONAL OPEN SCHOOL"
30 END
Keeping this program in view, let us go over the rules on the structure of the language.
These are:
Each statement of instruction must appear on a separate line.
20
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
A statement cannot exceed 80 characters i.e. one line on the terminal.
A statement must start with a statement number. It is a positive integer.
No two statements can have the same numbers.
The statement must be in the ascending order.
Each statement number is followed by a BASIC command or keyword.
You may use blank space to increase the readability of the program.
There is no restriction on blank lines within a program. These are the rules, as applicable to
standard or "Dartmouth BASIC" as it is called. The Microsoft BASIC i.e. BASICA or GWBASIC,
however, has provision for more than one statement in the same line and the use of keywords
also need not follow a line number. But if you strictly follow the rules of standard BASIC, the
program will still remain valid in Microsoft or any other BASIC. Now let us learn about some of
the keywords, you came across in the program.
REM
The REM is the short form for REMARKS. At the time of execution, when the interpreter comes
across the first three alphabets, as the keyword, it knows that the content of the line following
REM is not meant for execution and is to be ignored. REM is used purely to enhance the
documentation aspect of a program. It is meant for the reader of the program to understand the
contents, purpose, logic and other such aspects. Whatever, information on the program, you
want to convey to the reader of the program, may be placed after REM. There is no limit on the
number of REM statements in a program. In fact, it is recommended that you get used to
judicious and copious use of REM statements. It may not only help the reader, but it may also
help you in understanding your own programs, particularly if those are old or lengthy. At times to
enhance the presence of a REM statement you may place a blank line above or below a
statement. This makes it more visible in lengthy programs. You can place a blank line by a
21
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
PRINT statement. If we want to insert a blank line after the REM statement of the program, we
may write the program as:
END
The END statement was mandatory in the older BASIC version to indicate the end of a program.
In other BASIC like Microsoft BASIC, it is not compulsory. In such cases, the program terminates
at the last or highest line number. Whenever END is used, it must be the last line. Any statement
after the END is irrelevant to the interpreter. Having been familiarised with a small BASIC
program, let us now see the elements other than the keywords, comprising this language.
Numeric constant is one that is formed by a sequence of digits 0,1,2, ---, 9 and may include a
decimal point. A numeric constant known as number may be as integer or a real number. 383, +
57, 0, - 6.2 and 6.15E4 are valid numeric constants. The number 6.15E4, in fact, represent 6.15
22
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
104. The notation E is used to represent exponential form. The number after E is the exponent
which can be positive or negative. However, its length cannot exceed two digits.
Numeric variable can assume numeric value and is represented by an alphabet or an alphabet
followed by another alphabet or a digit. For example A, C, A2, ABC, A6 etc, represent numeric
variables. A string variable is represented by an alphabet followed by dollar ($) sign. It should be
kept in mind that while constructing the string variable, dollar ($) should be the last character. For
example, A1$, PKG$, BOOK1$, etc., are valid string variables.
Activities/Assessments:
1. The following numbers (constants) are not written correctly. Indicate the errors:
(a) 4,75,163,
(b) +-7567
(c) 3.64E 1.5
(d) 6.05E
(e) 6125 -
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
Overview:
24
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
An operator in a programming language is a symbol that tells the compiler or interpreter to
perform specific mathematical, relational or logical operation and produce final result. This
chapter will explain the concept of operators and it will take you through the important arithmetic
and relational operators.
Learning Objectives:
Course Materials:
ARITHMETIC EXPRESSIONS
A BASIC system can handle arithmetic expressions involving the five arithmetic operators +
(addition), - (subtraction), *(multiplication), /(division) and ^ (exponentiation). The hierarchy of
operations is as follows:
(i) Exponentiation
(ii) Multiplication and division
(iii) Addition and subtraction
Thus, in a particular arithmetic expression, the order of execution is as per this hierarchy, i.e. all
exponentiation operations are performed first, then multiplication/division and the
addition/subtraction operations are the last to be carried out. Note that within a particular
hierarchical group, the operations are executed form left to right. Normal hierarchy of operations
can be altered by use of parentheses. The operations within the innermost parentheses are
performed first and then the second innermost and so on.
In addition to this hierarchy of operations, the following rules must be kept in mind in arithmetic
expression:
Two operations must not appear together. For example, C+-D, A/-C, etc are not
permitted.
String constants and string variables should not be used in arithmetic expressions.
For example, P+P$ is wrong.
When brackets are used, they must be used in pairs, i.e., every left bracket must be
matched with a right bracket.
Denominator of an expression should not be zero.
Within a given pair of parentheses, the natural hierarchy of operations will apply.
Let us take an example where we give BASIC equivalents of a few algebraic expressions
In the execution of programs, it is sometimes desired to compare two numerical quantities (or
sometimes string quantities) and take decisions on achieving certain conditions. For example, we
may be interested to check the number of repetitive calculations performed or to find out whether
the denominator of an arithmetic expression has become zero or if a particular quantity is
negative, and so on. Expressions written to compare two quantities using certain relational
operators are known as relational expressions. These expressions take only one of the two
values, namely, TRUE or FALSE, For instance, the relational expression A > B will be true if A is
greater than B, otherwise FALSE. This test result is used to change the sequence of execution of
statements in a program. The general form of a relational expression is as follows:
Constant Constant
Relational
or or
operator
Variable Variable
When expressions are used on either side of the relational operators, the expressions will be
evaluated first and then the results of expressions compared. This means that relational
operators come last in the hierarchy of operators.
Logical expressions are used in IF---THEN Statements to determine the course of action of a
running program.
LOGICAL OPERATORS
Like relational operators, BASIC, also supports logical operators to perform logical operation on
numerical values. Logical operators are used to connect two or more relations and return a
TRUE or FALSE value to be used in a decision.
26
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
The common logical operators are:
AND Conjunction
OR Disjunction
NOT Logical Negation
For example, the expression A > 50 AND B > 150 is TRUE when A is more than 50 and at the
same time B is more than 150.
Logical operators return results as indicated in the following tables. T indicates a TRUE and F
indicates a FALSE. X and Y are relational expressions.
AND Operator
X Y X AND Y
T T T
T F F
F T F
F F F
OR Operator
X Y X OR Y
T T T
T F T
F T T
F F F
NOT Operator
X NOT X
T F
F T
The word `library' stands for collection. In the context of computer languages, a library is
essentially a collection of useful programs. These programs are used by the programmers to
simplify their task of program development. These programs are often referred as subroutines.
The programmer does not have to know the details of the sub-routine. Most of the programming
languages are offered with a number of sub-routines called sub-routine library or library
functions. These built-in library functions are used to simplify some useful common functions like
calculation of square root, log of a number or cosine of an angle. BASIC's library is rich with
mathematical functions. For example, suppose you want to calculate the square root of a
numeric variable A. In simple mathematics, square root of A, i.e., can be written as A ½. Thus in
BASIC it can be written as:
10 LET B = A^0.5
27
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
The value of B will be the square root of A. Using a library function the operation can be
performed as
10 LET B = SQR(A)
Of course, from the example, it appears that there is hardly any benefit in using the library
function. But imagine, if problem is little more complicated like calculation of the sine value of an
angle or logarithm of a number. The programming algorithm to calculate these is not so simple.
From this example, we may deduce the rules, governing the use of a function.
(a) Each function is assessed by the function name (LOG, SQR, etc.) followed by the function
argument placed within the parenthesis.
(b) The function argument is the information you supply to the function to act upon it. For
mathematical factions, it has to be a numeric constant or variable. Listed below are some
examples of mathematical functions in BASIC.
(d) You cannot have a blank space between function name (SIN, LOG etc.) and the beginning of
the opening parenthesis enclosing the argument.
It should be noted that a library function program would produce the result faster than a BASIC
program that has been written to perform the same task. For example, calculation of square root
by the SQR function will be faster than writing in the form of a program. This is due to the fact
that library functions are optimised for the particular BASIC interpreter provided by the supplier.
Activities/Assessments:
28
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(b) 2 * (3+4) / (5-3) * 7
2. Write the BASIC expression corresponding to each of the following algebraic expression:
(a) (x+y) 4
(b) 2x2 + 5x + 6
(c) x/y + y/z
(d) (x-y)4 / (x+y)4
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
29
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Overview:
Now we shall learn how the complete program in BASIC language can be written using the basic
principles we have learnt so far. For a computer program to be executed using a computer, we
should give some values to the computer. Once the computer, completes the required
computation work, we should ask the computer to produce the results in a proper format that can
be understood by the common man. The INPUT/OUTPUT statements of the BASIC language
achieve these two important functions. Besides these we shall also discuss the use of repetitive
and branching statements used in BASIC language.
Learning Objectives:
Course Materials:
In the previous lesson, we studied about the constants, the variables and the arithmetic operation
used in the BASIC language. We also saw how these constants, variables and the arithmetic
operations may be combined to form expressions and statements.
INPUT-OUTPUT STATEMENTS
It should be always kept in mind that computer cannot do anything by itself. It will act according
to the instructions supplied to it by the user. To achieve the required output in the desired format,
a user has to provide correct data and a series of processing instructions in proper order. In this
section, we will discuss various input/output statements provided in BASIC language.
As stated earlier, one of the basic features of a programming language is the input/output facility
offered by it. BASIC offers three such kinds of input statements. They are LET, INPUT and
READ-DATA. These statements are basically used to assign values to various variables.
LET Statements
Syntax:
These are all valid LET statements. The value of the variable on the left hand side of the equal to
sign is assigned the value given in the right hand side of the equal to sign
EXAMPLE
15 LET A =10
25 LET B =5
35 LET A = A+B
The example shows A is the variable name, which is, assigned the value 10 and B is the variable
name assigned the value 5. In the memory the line number 15 gives an instruction by which A
will be the address or name of a cell/location where the value 10 will be stored. Similarly B will be
name or address of a cell/location where 5 will be stored. Line number 35 instructs that the
values in the address A and B be added and the resulting value be kept at the cell/location
whose address is A.
A B
Execution of line 25 10 5
Execution of line 35 15 5
Note here that after execution of line 15 it has been shown “Not known” in location B, because in
this program we have not given any value to the variable name B on line number 15. It's value is
given in the next line number 25. Since variable A has been already given the value 10 that
continue to stay in A until we assign a different value to A which replaces the earlier value. So in
the next line number 35, A+B the values of A and B given before are added and put in the
31
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
location A Now the latest value of A is 15 and that of B will remain as 5. Let us suppose that line
35 has been replaced as
35 LET C = A + B
Here computer will add the values of A and B, i.e. 15 and put it in a third location C.
Line number 35 10 5 15
INPUT Statement
Syntax
EXAMPLE
12 INPUT A,B,X
16 INPUT A$,F$,N$
20 INPUT Y1,F$,C2,NB
Whenever computer reads a line with the keyword INPUT it displays a sign? on the VDU and
waits for the data. We have to give the values of the variable at this prompt through the
keyboard.
READ-DATA Statement
The LET and INPUT statement have certain limitations. By a LET statement we can assign one
value for each variable and if we have to get 10 values for 10 variables we have to use 10
statements with LET. Also if a value is assigned through a LET statement its value can be
changed only by replacing that assignment statement by another assignment statement. In case
of an input statement, the data is provided at the prompt at execution time. If there is a large
amount of data to be processed, it is inconvenient to key in the entire data during the execution
of the program. In such cases READ statements are found useful. READ statement will always
have a DATA statement along with it.
Syntax
32
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Line number READ Variable, List....
When the machine encounters the line number 5 with the READ statement followed by the
variables X2,Y,Z1,K it will collect from the DATA statements the values for these variables in the
same order. A one-to-one correspondence exists in READ-DATA statement, i.e. X2=8, Y=9,
Z1=13, K=15.
In the next READ statement in line number 9 we have four more variables A,B3,C4,L.
These values will follow in the same order and one-to-one correspondence after the earlier
READ variables values, i.e., after 8,9,13,15, i.e., A=16, B3=51, C4=30, L=92.
Since all the values in the DATA here are exhausted, another i.e. third, READ statement cannot
be used until another DATA statement is included or more DATA is included in the above DATA
list in line number 22. A DATA statement can be anywhere in the program but must be before the
END statement. It is a normal practice to keep all DATA statements together at the end of the
program before END statement, so that in case you want to alter any data at the end it will be
easy.
DATA BLOCK
The BASIC organises the contents of all the DATA statements into a data block. When the READ
statement are executed a pointer moves along with data block starting from the first element:
EXAMPLE
1 READ X1, Y1, Z1
7 READ N, M, L, K
12 READ A
19 READ X,Y
24 DATA 122
26 DATA-35,49, -101
28 DATA -691,81
30 DATA 8,10.-5,5
40 END
DATA BLOCK
Now look at the following some examples where all the programs do exactly the same work.
(d) 10 READ A$
20 READ B$,A,B,C
30 DATA "RAMA"
40 DATA "DELHI"
50 DATA 100,200,300
-------------
100 END
In all these cases A$ is assigned the value RAMA and B$ the value DELHI.All the numeric
variables A,B,C are assigned the values 100,200,300 respectively.
34
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
should be there in the DATA statement. It may be more. If the number of values in DATA
is less, then there will be an error message OUT OF DATA given by the computer.
The type of variables (i.e., numeric, string) in the READ statements containing many
variables.
Although normally we keep all the DATA statements at the end of the program just before
END statement, DATA statement can occur anywhere in the program but before END
statement.
Restore Statement
The RESTORE statement beings the pointer to the first value of the DATA statement regardless
of the current position of the pointer.
Syntax
For example,
10 RESTORE
The RESTORE statements may be used anywhere in the program, of course, before the END
statement.
The following example will clearly illustrates the use of RESTORE statement
10 READ X,Y
20 DATA 10,12,-7,3.2, "PANKAJ"
30 RESTORE
40 READ A,B,C,D,N$
50 END
When the statement number 10 is executed, the variables X and Y are assigned the values of 10
and 12, the position of the pointer at this stage is shown below:
10 12 -7 3.2 "PANKAJ"
(Pointer)
When the statement 30 RESTORE is executed, the pointer is brought back to the first data value
of data statement as shown below:
10 12 -7 3.2 "PANKAJ"
( Pointer)
Now, the execution of the statement number 40 against the value to A,B,C,D and N$ will be as
35
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
shown below:
A 10
B 12
C -7
D 3.2
N$ PANKAJ
and
If the key word RESTORE is followed by asterisk (*), then only numeric pointer is reset as shown
in the previous example. However, if the key word RESTORE is followed by a dollar sign ($),
then only string pointer is reset to the first string data. The simultaneous use of both asterisk (*)
and dollar sign ($) is not allowed.
10 READ A,B,N$,M$
20 -------
30 -------
40 RESTORE *
50 READ P,Q,A$,B$
60 -------
70 -------
80 DATA 5,8,"DINESH",UPMA",10,12,"RAJESH","SANJU"
90 END
When the statement 10 is executed, A,B are assigned values 5 and 8 whereas the variables N$
and M$ are assigned the values DINESH and UPMA respectively. The execution of statement
40, restores the numeric pointer to the first numeric value in the DATA statement i.e. to the value
5. The execution of the statement 50, assigns the value 5,8, RAJESH and SANJU respectively to
the variable P,Q,A$ and B$. The values DINESH and UPMA are being ignored. Similarly, the
execution of RESTORE$ can also shown by taking similar example.
10 READ A,B,N$,M$
20 RESTORE $
30 READ P,Q,A$,B$
36
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
40 DATA 5,8, "DINESH", "UPMA", 10,12,"RAJESH",SANJU"
50 END
Here the statement RESTORE$ is used. The values assigned to the variable A,B,N$ and M$ are
same as in the previous example. However, when statement 20 is executed, the string pointer is
reset to the first string data namely DINESH. The execution of the statement 30 would assign the
values 10 and 12 to the variables P and Q and then the pointer moves back-ward to assign the
values DINESH and UPMA to the variables A$ and B$
PRINT STATEMENT
The PRINT statement of BASIC provides limited methods of controlling the alignment and
spacing of printout in terminals. The general from of the PRINT statement is
Program
10 LET S =1175.50
30 END
T O T A L S A L A R Y = 1 1 7 5 . 5 0 R U P E E S
Using semicolon in a print statement, the items are close to each other, and as a result more
items can be printed in one line,
1 17 33 49 65 85
37
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
65 -15.56 36 34
The number of columns in each zone may be checked from the literature of manual for the given
computer.
The PRINT USING statement is included in most versions of microcomputer BASIC. It allows
printed output to be formatted, giving the appearance of each data item. This PRINT USING
statement can specify both string and numeric data.
There are several different ways to format. The most commonly used are given below:
The format string "##. ##", which a numeric field containing a decimal point with not more than
two digits on each side.
10 LET A =17.32
20 LET B = -5.38
30 LET C =40
40 PRINT USING "##. ##",A,B,C,
50 END
OUTPUT
If string values are used instead of numeric values, the format string for PRINT USING will be as
follows:
If N$ ="UNITED"
Then the above PRINT USING statement will give output as:
UNITED
Observe, there are six alphabets and we have used six exclamation sign (!). Each exclamation
sign (!) is used to represent each character of a string.
Example
If N$ = "FROG" then
38
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(a) 100 PRINT USING "!!!!";N$ gives output as bbFROG
Since "!!!!!!" has six character representations and FROG has only four characters,">" sign gives
characters b b in the left side as the PRINT USING with > gives right justified. Space characters
(b b ) are used to fill left space.
TAB FUNCTION
The TAB (abbreviation of TABULATION) function is a very important function because it enables
the user to exercise exact control over the print positions. The use of a COMMA and a
SEMICOLON to space out the output is not so flexible as the TAB function.
TAB (n) moves the printer head to the nth column and printout of any data starts from that column.
Syntax:
Where N is a positive number, a variable or an expression having positive value and X shows
output data
(a) If N is an integer, the printer head moves to the Nth column and printing of the value of X
starts from that column
(b) In case N is a variable, not having the internal value, it is rounded and the printer head moves
according to this value.
For example,
5 X = 12
10 K = 5.3
20 PRINT TAB(k) ; X
(c) On the other hand, if N is an expression then first of all, the expression is evaluated and
rounded, if necessary. The printer head move based on the value of this expression.
39
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
For example, consider the statement
Here TAB (25) instructs the computer to start printing DINESH from column number 25 onwards.
Then TAB (20) instructs the computer to write RAJESH from column 20. Since the printer head is
already beyond the column 20 and backward movement is not allowed, so TAB (20) is ignored
and the output is same as if TAB (20) was not present. The above statement is equivalent to
The comma preceding the function TAB (10) Positions the printer head to the column 16 so that
the function TAB (10) becomes redundant as printer head cannot move backward and hence it is
ignored. The value 15.6 will be printer from column 16 onwards.
The use of TAB function is an elegant method to prepare patterns, producing tables and to plot
graphs etc.
We have already seen a few BASIC statement like REM, (in Lesson 1),and
LET,INPUT,READ,DATA etc in this Lesson itself. The other few BASIC statements and their
explanations are given in this section. We will discuss them in details using different program.
Unconditional Go To Statement
GOTO statement is used to transfer control from a statement, say S1 to another statement, say
S2, generally, S2 does not follow S1 immediately in sequence.
Syntax: Line number GO TO n
n is the line number of the statement where control will be transferred.
Program 1
10 READ A,B,X,Y
20 GO TO 60
30 LET X = X*X+A
40 LET Y=Y*Y +B
40
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
50 PRINT X, Y
60 LET X =A*X
70 LET Y =B*Y
80 PRINT X,Y
90 DATA 6,3,4,5
100 END
This shows after reading the values of A,B,X,Y, in line number 10, the control jumps to line
number 60 and calculate X =A*X, Y =B*Y then prints X,Y in line number 80 and ends the
program. Line number 30,40,50 are never executed. If we want to execute 30,40,50 then our
program will add few more jump statements, i.e. few more GO TO statements.
Consider the following program 2.
Program 2
10 READ A,B,X,Y
20 GO TO 60
30 LET X =X*X+A
40 LET Y =Y*Y+B
50 PRINT X,Y
55 GO TO 100
60 LET X =A*X
70 LET Y =B*Y
80 PRINT X,Y
85 GO TO 30
90 DATA 6,3,4,5
100 END
Thus by introducing line number 55 and 85 all the statements are executed. So line number 30
and 40 prints X =X*X +A (value), Y =Y*Y+B (value) and line number 80 prints X = A*X and Y
=B*Y
Activities/Assessments:
IN-TEXT QUESTION1
(a) In the LET statement, the value of a variable on the ......... hand side of the equal to sign is
assigned to the variable given in the .......... hand side of the equal to sign.
(b) READ statement cannot be used without a ........... statement.
41
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(c) DATA statement can occur anywhere in the program, but must be before the ...........
statement.
2. State the difference between READ and INPUT statement?
3. What is the use of PRINT USING statement?
4. What is the use of RESTORE statement?
5. Define briefly the use of TAB function.
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
Overview:
Decision making is critical to computer programming. There will be many situations when you will
be given two or more options and you will have to select an option based on the given
conditions..
42
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Learning Objectives:
Course Materials:
EXAMPLE 2
Evaluate the expression Y =X2 for X =1,2,3...
Program 1
10 LET X = 1
20 LET Y = X*X
30 PRINT Y
40 LET X = X+1
50 GO TO 20
60 END
In this process we see each time the line number 50 is executed the control is transferred to line
number 20 unconditionally. Thus we have an infinite loop which is never ending.
Computer goes round and round and never reaches END
To stop the infinite loop we can add a condition, i.e. say if X is greater than or equal to 31 (X
>=31) then the program ends otherwise it keeps on printing the value of expression Y = X2 for X
=1,2,3....30.
Program 2
10 LET X = 1
20 LET Y = X*X
30 PRINT Y
40 LET X = X+1
50 IF X> = 31 THEN 70
60 GO TO 20
70 END
43
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Thus we see that IF-THEN is one of the powerful statements which can stop or get the
computer out of an infinite loop.
EXAMPLE 3
Problem 1
Write a program to find out the auto fare depending on the Kilometers traveled. The minimum
fare charged is Rs. 3.00. This minimum fare remains for 2 kms or less of travel. After 2 kms, the
charges are 75 rp per kilometer.
Program 1
10 INPUT "KILOMETER", K
20 IF K < = 2 THEN PRINT "RS.3” : END
30 LET CHARGE =3+ (K-2) *.75
40 PRINT CHARGE
50 END
Here in line number 20, if K is less than or equal to 2 (i.e., K<=2) then it will print Rs. 3 and (:
END) means END, in continuation to the line number 20 next statement is END.
Otherwise if K is not less than or equal to 2 then line number 30,40 then 50 will be executed.
EXAMPLE 4
Problem 1
Ages of different students appearing in the Board examination are taken. If the age is below 17
the student is not eligible, otherwise he can appear in the Board examination. We are asked to
write a program for this problem.
Program 1
10 INPUT “AGE”; A
20 IF A>= 17 THEN 30 ELSE 50
30 PRINT “WELCOME FOR BOARD EXAMINATION”
40 GO TO 60
50 PRINT “YOU ARE NOT ELIGIBLE FOR BOARD EXAM.”
60 INPUT “WANT TO INPUT AGAIN (Y/N)”; Y$
70 IF Y$ = “Y” THEN 10
44
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
80 END
The line number 10 will cause the message in screen AGE? We input the age through the
keyboard, say 18. Line number 20 tests whether A>17 or not. Since A=18>17 line number 30 is
executed.
Line number 30 prints WELCOME FOR BOARD
Line number 40 causes the control to pass to line number 60.
Line number 60 causes the message WANT TO INPUT AGAIN (Y/N)? We input either Y or N.
In line number 70 if input is Y then control goes to line number 10. Otherwise if input is N then
control goes to the line number 80 i.e. END.
Now if in line number 70 we input Y then control will pass again line number 10, we give another
age, say 13
In line number 20 value of A (i.e. 13) is not greater than 17, therefore ELSE part will be executed
and control will go to line number 50. Line number 50 will print YOU ARE NOT ELIGIBLE FOR
BOARD EXAM. Then line number 60 as before will be executed. In this way a large number of
students age can be tested. When we want to stop we should input N in line 60 for Y$.
Problem 2
10 INPUT A,B,C
20 IF A>B AND A>C THEN 50 ELSE 30
30 IF B>A AND B>C THEN 60 ELSE 40
40 IF C>A AND C>B THEN 70
50 PRINT "A IS THE LARGEST NUMBER": GO TO 80
60 PRINT "B IS THE LARGEST NUMBER": GO TO 80
70 PRINT "C IS THE LARGEST NUMBER"
80 INPUT "WANT TO INPUT AGAIN (Y/N)" ; Y$
90 IF Y$ = "Y" THEN 10
100 END
In line number 20,30,40 comparisons are made among the values of A,B, and C.
AND is a logical operator which combines A>B and A>C. If both the relational expression
preceding and following AND are true then the line number following THEN will be executed
otherwise if one of the relational expression, A>B or A>C is true then the line number following
ELSE will be executed. Same procedure follows for the next two IF statements also.
If expression at 20 is found true, the line number 50 will print A is THE LARGEST VALUE and
then GO TO 80 will be executed as the next statement to line number 50. If it is found false the
control passes to statement 30 and the expression at that statement is checked. This part of the
program can also be written as follows:
45
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Thus line number 50 and 60 in earlier program of problem 2 is equivalent to line numbers
50,55,60,65 in the above program statement.
Syntax: For IF...THEN...ELSE with AND is given as;
This means if either of the conditions (or relational expression) followed or preceded by OR is
true then the instruction 1 is executed. If neither of them is true then instruction 2 is executed.
Decision making is critical to computer programming. There will be many situations when you
will be given two or more options and you will have to select an option based on the given
conditions. For example, we want to print a remark about a student based on his secured
marks. Following is the situation −
If given marks are less than 95 and more than 30, then
Student is average
Now, the question is how to write a programming code to handle such situations. Almost all the
programming languages provide conditional statements that work based on the following flow
diagram −
46
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Let's write a C program with the help of if conditional statements to convert the above given
situation into a programming code –
#include <stdio.h>
int main() {
int x = 45;
47
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Similarly, the second if statement works. Finally, the third if statement is executed, here we
have the following two conditions −
First condition is x > 95
Second condition is x < 30
The computer evaluates both the given conditions and then, the overall result is combined with
the help of the binary operator &&. If the final result is true, then the conditional statement will
be executed, otherwise no statement will be executed.
This tutorial will give you a basic idea on various forms of if statements and an introduction
to switch statements available in C programming language. Different programming languages
provide different types of decision-making statements, but the basic concept remains the same
as explained in this tutorial.
if...else statement
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false. The syntax of an if...else statement in C programming language is
−
if(boolean_expression) {
An if...else statement is useful when we have to take a decision out of two options. For
example, if a student secures more marks than 95, then the student is brilliant, otherwise no
such situation can be coded, as follows −
48
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
#include <stdio.h>
int main() {
int x = 45;
if...elseif...else statement
While using if, else if, else statements, there are a few points to keep in mind −
An if can have zero or one else's and it must come after an else if.
An if can have zero to many else…if's and they must come before the else.
Once an else…if succeeds, none of the remaining else…if's or else's will be tested.
if(boolean_expression 1) {
49
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Now with the help of if...elseif...else statement, the very first program can be coded as follows –
#include <stdio.h>
int main() {
int x = 45;
default :
statement(s);
}
The above syntax can be represented in the form of a flow diagram as shown below –
50
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Now, let's consider another example where we want to write the equivalent English word for a
given number. Then, it can be coded as follows –
#include <stdio.h>
int main() {
int x = 2;
switch( x ){
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
break;
default :
51
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
printf( "None of the above...\n");
}
}
Decisions in Java
Following is the equivalent program written in Java which too
supports if, if...else, if...elseif...else, and switch statements.
You can try to execute the following program to see the output, which must be identical to the
result generated by the above C example.
Student is average
Decisions in Python
You can try to execute the following program to see the output –
52
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
x = 45
if x > 95:
print "Student is brilliant"
elif x < 30:
print "Student is poor"
elif x < 95 and x > 30:
print "Student is average"
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
53
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Unit 3 Looping Constructs
Overview:
We have already seen that a loop can be built in BASIC by using the IF-THEN and GOTO
statements. When it is known in advance how many times the loop must be repeated the
statement FOR-TO...NEXT is the most effective statement. While statement is also used to
repeat certain actions while satisfying the condition.
Learning Objectives:
Course Materials:
Syntax:
Line number FOR I = M TO N STEP J
Loop - - - - - -
- - - - - -
Line number NEXT I
The numeric variable name following FOR is called the control variable or loop variable.
M and N are numeric constants where M gives the initial or starting value of the loop and N gives
the final value, J followed by keyboard STEP gives the increment in M till N is reached. The
increment can be negative also.
M,N,J can be numeric variable names. In such cases their numeric values should be assigned
before the starting of the loop, i.e. before coming to FOR-TO statement.
They key word NEXT should have the same control variable I followed by it. Thus one loop can
be started with FOR-TO and ended with NEXT.
Inside one FOR-TO ...NEXT loop there can be more FOR-TO...NEXT loop. But once a FOR-
TO...NEXT is inside another FOR-TO...NEXT, it should remain completely inside the former loop.
Such FOR-TO...NEXT loops are called Nested loops. In the absence of the STEP clause, the
increment is assumed to be 1.
54
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
EXAMPLE
Problem 1
Suppose we want to print the output in the following format:
*****
****
***
**
*
Program 1
10 FOR S=5 TO 1 STEP-1
20 FOR X=1 TO S
30 PRINT "*" ;
40 NEXT X
50 PRINT
60 NEXT S
70 END
This program contains two loops: the outer loop is from the line number 10 to 60 and inner loop
from line numbers 20 to 40. In line number 10, initially S is assigned a value 5. Since the value of
S is greater than 1, control is transferred to line number 20, which causes the inner loop to
execute 5 times resulting into printing of 5 stars (*) in one row. The statement at line number 50
will transfer the printer control to the beginning of the next line. When line 60 is encountered, the
control goes back to line number 10. Now the value of S becomes 4 and once again the inner
loop is executed 4 times resulting in printing of 4 (*) stars in second row. This process will
continue till the value of S becomes 1. After that it will come to end.
Problem 2
Suppose we want to sum to following series:
1,2,3,4_ _ _ _ 100.
Program 2
10 LET S=0
20 FOR I=1 TO 100
30 LET S=S+I
40 NEXT I
50 PRINT " SUM OF SERIES =" ; S
60 END
The GOTO statement allows only one transfer point, IF...THEN allows two transfer points, the
ON...GOTO can have more than two transfer points, thus providing multiple branching facility.
Syntax: line number ON (Numeric variable or expression) GOTO n1,.n2,n3,..
The expression is a valid BASIC expression and n1,n2,n3,.... are the statement numbers or line
number where the control will be transferred.
55
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
If ON is followed by numeric variable name and if the value of numeric variable is 1 control is
transferred to n1, if 2 then n2, if 3 then n3 and so on.
EXAMPLE
Problem
Write a program to add, subtract, divide and multiply two numbers A and B.
Program
5 INPUT A,B
10 INPUT " 1-ADD, 2-SUB, 3-MUL, 4-DIV"; N
20 ON N GOTO 30,40,50,60
30 PRINT A+B : END
40 PRINT A-B : END
50 PRINT A*B : END
60 PRINT A/B : END
When line 5 is executed, there will be question mark (?) then you have to input the values of A
and B through keyboard. Line number 10 will cause a message on the screen 1-ADD, 2-SUB, 3-
MUL, 4-DIV and then display of question mark (?) for N.
If we input through keyboard 1 then N takes the value 1.If we enter 2 or 3 or 4,N will take 2 or 3
or 4 accordingly. If the value of N is
On execution of line number 30 addition of A and B will be displayed on the screen and program
will come to an end. Similarly, in line number 40,50,60 printing of the result of subtraction,
multiplication and division will be displayed respectively.
Let's consider a situation when you want to print Hello, World! five times. Here is a simple C
program to do the same –
#include <stdio.h>
int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
56
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
printf( "Hello, World!\n");
printf( "Hello, World!\n");
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
It was simple, but again, let's consider another situation when you want to write Hello, World! a
thousand times. We can certainly not write printf() statements a thousand times. Almost all the
programming languages provide a concept called loop, which helps in executing one or more
statements up to a desired number of times. All high-level programming languages provide
various forms of loops, which can be used to execute one or more statements repeatedly.
Let's write the above C program with the help of a while loop and later, we will discuss how this
loop works
#include <stdio.h>
int main() {
int i = 0;
while ( i < 5 ) {
printf( "Hello, World!\n");
i = i + 1;
}
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
The above program makes use of a while loop, which is being used to execute a set of
programming statements enclosed within {....}. Here, the computer first checks whether the
given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then the
loop body is entered to execute the given statements. Here, we have the following two
statements in the loop body −
First statement is printf() function, which prints Hello World!
Second statement is i = i + 1, which is used to increase the value of variable i
After executing all the statements given in the loop body, the computer goes back to while( i < 5)
and the given condition, (i < 5), is checked again, and the loop is executed again if the condition
holds true. This process repeats till the given condition remains true which means variable "a"
has a value less than 5.
57
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
To conclude, a loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the programming
languages –
This tutorial has been designed to present programming's basic concepts to non-programmers,
so let's discuss the two most important loops available in C programming language. Once you
are clear about these two loops, then you can pick-up C programming tutorial or a reference
book and check other loops available in C and the way they work.
58
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
The following important points are to be noted about a while loop −
A while loop starts with a keyword while followed by a condition enclosed in ( ).
Further to the while() statement, you will have the body of the loop enclosed in curly
braces {...}.
A while loop body can have one or more lines of source code to be executed repeatedly.
If the body of a while loop has just one line, then its optional to use curly braces {...}.
A while loop keeps executing its body till a given condition holds true. As soon as the
condition becomes false, the while loop comes out and continues executing from the
immediate next statement after the while loop body.
A condition is usually a relational statement, which is evaluated to either true or false. A
value equal to zero is treated as false and any non-zero value works like true.
The above code can be represented in the form of a flow diagram as shown below –
59
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
If you will write the above example using do...while loop, then Hello, World will produce the
same result –
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
}
while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
When the break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop. The syntax for
a break statement in C is as follows −
break;
A break statement can be represented in the form of a flow diagram as shown below −
60
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Following is a variant of the above program, but it will come out after printing Hello World! only
three times −
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
if( i == 3 ) {
break;
}
}
while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
61
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Following is a variant of the above program, but it will skip printing when the variable has a
value equal to 3 −
#include <stdio.h>
int main() {
int i = 0;
do {
if( i == 3 ) {
i = i + 1;
continue;
}
printf( "Hello, World!\n");
i = i + 1;
}
while ( i < 5 );
}
Loops in Java
while ( i < 5 ) {
System.out.println("Hello, World!");
i = i + 1;
}
}
}
Loops in Python
62
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Following is the equivalent program written in Python. Python too
supports while and do...while loops. The following program prints Hello, World! five times as
we did in case of C Programming. Here you must note that Python does not make use of curly
braces for the loop body, instead it simply identifies the body of the loop using indentation of the
statements.
You can try to execute the following program to see the output. To show the difference, we have
used one more print statement, which will be executed when the loop will be over.
i=0
Loop ends
Activities/Assessments:
2. In the following FOR statements, write the values taken by the control variable
(a) 10 FOR L = 3 TO 12 STEP 2
(b) 20 FOR M = 1 TO 50 STEP 10
(c) 30 FOR N = 100 TO 0 STEP -20
(d) 40 FOR K = 5 TO 5
(e) 50 FOR I = 10 TO 6 STEP -1
5. Write a program in BASIC to print out the largest number out of 10 given numbers.
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
64
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Lesson 4 - Handling of Arrays, Functions and Sub-Routine
Unit 1 Arrays
Overview:
In the previous lesson, you have gone through the programming technique and various
INPUT/OUTPUT and control statements in BASIC. But the features that make this programming
language more useful are use of subscripted variables, subroutine and various functions
provided to help the programmer. We shall be discussing all these features in this lesson. We
have also included various sample programs, which will help you further in writing more complex
programs in BASIC language.
Learning Objectives:
This lesson will explain you about handling of lists, tables, subroutine, sub-programs and some of
the functions of BASIC. At the end of this lesson, you should be able to:
use functions and subroutines in BASIC language
write complex programs in BASIC language
learn how to set up and use arrays in BASIC programs
Course Materials:
Example 1: suppose we want to represent five numbers (10,12,42,91,7,) which represent the
marks of five students
Solution:
We can use an array name M(I) which is also called the subscripted variable and I is the
subscript which varies from 1 to 5. M is the name of array and M(1) is an element of the array M.
M(1) 10
65
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
M(2) 12
M(3) 42
M(4) 91
M(5) 7
Problem1: Write a program to read the above data into the memory.
Program 1
10 DIM M(5)
20 FOR I = 1 TO 5
30 READ M(I)
40 NEXT I
50 DATA 10,12,42,91,7
60 END
Example 2: We have an item biscuit in a shop. We have prices for 10 different biscuits as 60,
45.5, 32.6, 19.5, 52, 49,53.75, 29, 43, 38.6. We write a program to print these different values or
we want to know the price of any type of the above biscuits. We will do it by using an array.
Solution
Since they are similar items, we give them a single name BISCUIT or in short BIS. Since we
know only one specification i.e. price we have a single subscript, say I. So the array is now
BIS(I). Since there are 10 prices for 10 types of biscuits I varies from 1 to 10 i.e. BIS(1), BIS(2)
…….BIS(10).
If we want to know the price for the biscuit of type 4, we will print BIS(4) which will give us the
required price.
Program 2
10 DIM BIS(10)
20 REM PRICES FOR 10 TYPES OF BISCUITS ARE TO BE READ
30 REM THE 10 PRICES HAS TO BE PRINTED ALSO
\40 FOR I = 1 TO 10
50 READ BIS(I)
60 NEXT I
70 PRINT “THE PRICES OF TEN DIFFERENT BISCUITS”
80 FOR I =1 TO10
90 PRINT BIS(I)
100 NEXT I
110 DATA 60,45.5, 32.6, 19.5, 52,49,53.75
120 DATA 29,43,38.6
130 END
66
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
OUTPUT
Line number 70 will print
THE PRICES OF TEN DIFFERENT BISCUITS
The line number 10 DIM BIS(10) is compulsory. This informs the machine that we are giving an
array with single subscript having 10 elements. So, 10 cells in the memory location will be kept
for the variable name BIS.
If we want an array of strings instead of numeric value, see the following example:
Example 3
To store the names of six motor cars in any array (table) such as:
Program 3
10 REM DECLARE THE NAME AND SIZE OF THE TABLE
20 DIM C$(6)
30 REM… USE THE READ/DATA TECHNIQUE
40 REM TO STORE STRINGS
50 FOR J = 1TO 6
60 READ C$(J)
70 NEXT J
80 REM.. NOTE THE STRINGS USED AS DATA ARE
90 REM.. ENCLOSED BETWEEN QUOTATION MARKS
100 REM.. ARRAY NAME TO STORE STRINGS IS
110 REM.. GIVEN AN STRING VARIABLE NAME C$
120 DATA “FORD”, “MARUTI”, “AMBASSADOR”
130 DATA “FIAT”, “STANDARD”, “VAUXHALL”
140 END
The REM (i.e. remarks) given in the line number 30,40,80,90,100,110, explains the program.
Though DATA is given in two lines 120 to 130, the data should be in the order they are placed.
C$(1) = “FORD”
67
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
C$(2) = “MARUTI”
C$(3) = “AMBASSADOR”
C$(4) = “FIAT”
C$(5) = “STANDARD”
C$(6) = “VAUXHAULL”
Example 4
Let the 10 data values are given as 4, -6, 7, 2.3, - 6.1, 5. 3
-1, 0, - 2.7,9
WE give this set of values the name, say VAR (I) where I is the subscript.
If I = 1, then VAR (1) has the value 4
I = 5, then VAR (5) has the value -6.1
I = 8 then VAR (8) has the value 0, and so on.
Program 4
10 REM ADDING 10 NUMBERS IN A ONE DIMENSIONAL TABLE
12 DIM VAR (10)
15 LET SUM = 0
20 FOR I = 1 TO 10
30 READ VAR (I)
40 LET SUM = SUM +VAR (I)
50 NEXT I
60 DATA 4, -6,7, 2.3, -6.1, 5.3, -1, 0, -2.7,9
70 PRINT SUM
80 END
By using this statement in line number 10 of the program 1 above, the array whose name is M
has been allotted 5 cells in the memory location. Syntax for the DIM statement is
Line number DIM array name (unsigned integer)
The unsigned integer specifies the size of the array variable.
If we write 10 DIM A(100), X(10), then 100 locations are reserved for the array name A and 10
locations for the array name X.
DIM should be the first statement in the program barring REM statement.
Problem 5
68
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Suppose we want to read the roll number of a student and his marks obtained in five subjects in
the board examination. Now print the roll number and average marks secured by him.
Program 5
10 DIM M(5)
20 INPUT ROLLNO
25 LET TOT = 0
30 FOR I = 1 TO 5
40 READ M(I)
50 LET TOT = TOT + M(I)
60 NEXT I
70 LET AVERAGE = TOT/5
80 PRINT ROLLNO, AVERAGE
90 DATA 60,52,49,80,72
100 END
On the execution of line number 30, initially the control variable I becomes 1 and line number 40
reads M(I), i.e. the first mark from line number 90, that is 60 and adds to the variable TOT which
is initially zero. So for I = 1 line 50 gives TOT = 0 +60 = 60, control then goes to line number 60
and back to 30. Now I becomes 2 and line number 40 reads M(2), i.e. 2nd marks from DATA, i.e.
52. In line number 50 TOT = 60 + M(2), i.e. TOT = 60+52 = 112 and so on. So line number 30 to
60 is executed five times. Thus finally in the variable name TOT we have TOT =
60+52+49+80+72=313.
So, when line number 70 is executed AVERAGE = 313/5 =62.6. Line number 80 will print the
ROLLNO which is entered in line number 20 and the average AVERAGE as 62.6.
If we want to do this process for a large number of students say 10 we have to give more data in
DATA statement, i.e. 45 more data values and put another loop to repeat the process for ten
students.
Program 5(a)
10 DIM M (5)
15 FOR J = 1 TO 10
20 INPUT ROLLNO
25 LET TOT =0
30 FOR I = 1 TO 5
40 READ M (I)
50 LET TOT = TOT + M(I)
60 NEXT I
70 LET AVERAGE = TOT/5
80 PRINT ROLLNO, AVERAGE
85 NEXT J
90 DATA 60,52,49,80,72,98,69,72,80,75
100 DATA 88,61,54,48,60,52,92,86,81,65
110 DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
69
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
120 DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
130 DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
140 END
Thus we see TABLE (I,J) has 3 rows, i.e. I = 1 TO 3 and 4 columns, i.e. J = 1 TO 4.
Problem 6
We want to read and print the values of TABLE (I,J) as given above
Program 6
10 DIM TABLE (3,4)
15 FOR I = 1 TO 3
20 FOR J = 1 TO 4
30 READ TABLE (I,J)
35 PRINT TABLE (I,J)
40 NEXT J
50 NEXT I
70 DATA 2,4,8,10,1,3,5,7,3,7,13,17,
80 END
See how it reads the data
As the subscript J corresponding to the column is in the inner FOR loop, the table is read row-
wise. J being in the inner loop changes more frequently from 1 to 4 for every value of I, which is
in the outer loop. If we want to read the data column-wise program will be as follows.
Program 7
70
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
10 DIM TABLE (3,4)
20 FOR J =1 TO 4
30 FOR I =1 TO 3
40 READ TABLE (I, J)
50 NEXT I
60 NEXT J
70 DATA 2, 1, 3, 4, 3, 7, 8, 5, 13, 10, 7, 17
80 END
More applications relating to subscripted variables will be shown in the last section. We have
shown you to store numeric data in a table (array) with row and column subscripts. Now, you will
see how string data is stored in a two-dimensional array.
Example
The following are data values (names), which are to be stored in the table form with rows and
columns.
Program 7
10 REM DECLARE THE NAME AND SIZE OF THE TABLE
20 DIM N$ (2,4)
30 REM SET UP AN OUTER LOOP TO CONTROL THE ROW SUBSCRIPT
40 FOR M = 1 TO 2
50 REM…..SET UP AN INNER LOOP TO CONTROL THE COLUMN SUBSCRIPT
60 FOR P = 1 TO 4
70 REM .. USE A READ/DATA STATEMENT TO STORE DATA AS
80 REM .. SHOWN IN DIAGRAM
90 READ N$ (M, P)
100 NEXT P
110 NEXT M
120 DATA "HARIOM", "DINESH" "RAJESH"
130 DATA "PANKAJ", "BIMLA"
140 DATA "UPMA", "SANJU", "ANAMIKA"
150 END
Activities/Assessments:
71
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
1. Given the following code:
10 LET S =0
20 FOR I = 1 TO N STEP 2
30 LET S = S+2*I-1
40 NEXT I
50 END
You are required to complete each statement.
(a) The accumulator is the variable ___________
(b) The control variable is _______________
(c) After execution, S contains the sum of the first N _________ Integers.
(b) 10 LET S = 0
20 FOR I = 1 TO 10
30 LET S = S + I
40 PRINT S
50 NEXT K
72
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
25 30 35 40
(a) What are the values of FAX (1,3) and FAX (2,1) ?
(b) Which elements of FAX contain the numbers 30 and 20 ?
7. Write a BASIC program that determines and prints the smallest and largest elements of a
two-dimensional array (assuming that it; has been already inputted) with four rows and five
columns.
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing. You
have already seen various functions like printf() and main(). These are called built-in functions
provided by the language itself, but we can write our own functions as well and this tutorial will
teach you how to write and use those functions in C programming language.
Good thing about functions is that they are famous with several names. Different programming
languages name them differently, for example, functions, methods, sub-routines, procedures, etc.
If you come across any such terminology, then just imagine about the same concept, which we
are going to discuss in this tutorial.
Learning Objectives:
In this lesson we have discussed various statements relating to decision making, looping and
branching. Use of subroutine, sub-programs and arrays has been explained clearly by taking
number of examples. These commands play very important role in writing programs. The
illustrations given in this lesson will help you for a better grasp of BASIC programming. Usage of
some BASIC functions has been clearly defined for the benefit of the students.
Course Materials:
Where “V” is the one-letter name of the function and "a" is the argument, which appears as a
variable in the expression on the right.
Problem 1
Suppose we want to write a program to calculate y for various values of x, say for x = 1,2,3,4,5,
for the expression y(x) =ax2 + bx + c
Program 1
74
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
10 DEF FNY (X) = A*X*X + B*X + C
20 INPUT A, B, C
30 FOR X = 1 TO 5
40 PRINT X, FNY(X)
50 NEXT X
60 END
On execution of the program line number 30 TO 50 will give the value of y(1) through y(5) for the
respective value of x, calculated at line number 10. The value of x is supplied in line number 30
and values of A, B and C are input at line 20.
Problem 2
Let us consider the program to calculate
y = 1.5x + 3 for x<= 2
y = 2x + 5 for x>2
Program 2
100 DEF FNY(X)
105 INPUT X
110 IF X < = 2 THEN 140
120 LET FNY = 2*X + 5
130 GO TO 150
140 LET FNY = 1.5*X + 3
150 FNEND
170 PRINT X, FNY(X)
180 END
Here DEF FNY (X) statement in line number 100 is used without being equated to expression.
The FNEND statement in line number 150 indicates the end of the function. The line numbers
160 to 180 consist the main program. On execution of line 170 a call to the function FNY(X) is
made causing the execution of line number 100 to 150 with the input value of X.
The DEF statement must have DEF FN and variable name with one character and arguments
included in the parenthesis. Arguments can be more than one also. The argument is a variable,
which must appear in the right side after the equal to (=) sign, in case of DEF FN statement is
equated to an expression. (For example, see problem 1)
Example 1
Evaluate the algebraic formula z =(u/v + x/y)/2 for different set of values of u, v, x, y.
Solution
10 DEF FNZ(U,V,X,Y) =(U/V + X/Y)/2
20 INPUT U,V,X,Y
30 PRINT FNZ(U,V,X,Y)
40 END
75
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
This is for one set of values for U,V,X,Y. Now the program given below will evaluate the formula
for different set of values for U,V,X,Y
10 DEF FNZ (U,V,X,Y) = (U/V + X/Y)/2
20 INPUT U,V,X,Y
30 PRINT FNZ(U,V,X,Y)
35 IF U = O THEN 50
40 GO TO 20
50 END
Line number 40 sends the control back to INPUT. Now, you can enter another set of values for
U,V,X,Y. When you want to stop, you enter O for U. Then line number 35 will bring the program
to END.
Example 2
Define a function for subprogram for the algebraic formula
p = log(t2 -a) for t2 > a
log(t2) for t2 = < a
Solution
30 DEF FNP(T,A)
40 INPUT T,A
50 IF T * T < = A THEN 80
60 LET FNP =LOG (T ^ 2 -A)
70 GO TO 90
80 LET FNP = LOG (T ^ 2)
90 FNEND
100 PRINT T, A FNP (T,A)
110 END
In line number 40, the values of T,A can be input by READ/DATA or by using LET statements
twice.
Note: Please consult the machine manual for DEFFN statement before running the programs in
the machine.
GOSUB Statement
Syntax: line number GOSUB n
Where n is the line number of the 1st statement in the subroutine.
Subroutines are placed at the end of the main programs in order to repeat a process. The
program control has to exit from the main program to enter a subroutine and after the process is
completed it comes back to the main program using RETURN statement.
76
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
RETURN statement
Syntax: line number RETURN
The RETURN statement in the subroutine transfers the control back to the main program to the
line immediately following the corresponding GOSUB statement. RETURN is the last statement
in the subroutine.
GOSUB and RETURN are always used together in the program not independently.
Properties of GOSUB
One subroutine can follow another subroutine but each subroutine should be complete within
itself.
GOSUB unconditionally transfers the program from the main to the subroutine.
GOSUB can also transfer the program conditionally by using it with IF-THEN ELSE
Syntax: Line number IF (Logical expression) THEN COSUB (line number) ELSE GOSUB (line
number)
A subroutine can be called by the main program a number of times. But the returning point
will be different in each time.
GOSUB takes the control from the main program to the subroutine and return brings back the
control from the subroutine to the main program.
Problem 1
Write a program to add, subtract, multiply and divide any two numbers.
10 INPUT A, B
20 INPUT "CHOICE", C$
30 IF C$ = "ADD" THEN GOSUB 80 : GOTO 65
40 IF C$ = "SUB" THEN GOSUB 120 : GOTO 65
50 IF C$ = "MUL" THEN GOSUB 170 : GOTO 65
60 IF C$ = "DIV" THEN GOSUB 210
65 PRINT C
70 END
80 REM "SUBROUTINE FOR ADDITION"
90 LET C = A + B
91 RETURN
120 REM "SUBROUTINE FOR SUBTRACTION"
130 LET C =A-B
150 RETURN
170 REM "SUBROUTINE FOR MULTIPLICATION"
180 LET C = A*B
200 RETURN
210 REM "SUBROUTINE FOR DIVISION"
220 LET C = A/B
240 RETURN
77
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Short form of Problem 1 for addition
10 INPUT A, B
20 INPUT "CHOICE" C$
30 IF C$ = "ADD" THEN GOSUB 50
40 END
50 PRINT A+B
60 RETURN
So whatever will be the input of C$ in line number 20, GOSUB will go to these subroutines as it is
written for C$ = "ADD" similar subroutines will follow for "SUB", "MUL", "DIV" ON GOSUB
statement is similar to ON GOTO.
Syntax is given as:
Activities/Assessments:
1. Answer briefly:
(a) What is a subscripted variable?
(b) What is the function of a DIM statement?
(c) Define a subroutine?
(d) What does a RETURN statement do?
78
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(b) 10 DEF FNA (W) = 2*W+1
20 PRINT FNA (2)
30 LET x = 3
40 PRINT SQR (FNA (x+1))
50 END
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
79
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Unit 3 Strings Statements
Overview:
Learning Objectives:
After this lesson, you will be able manipulate data by the use of different functions
Course Materials:
EXAMPLES AND PROGRAMS SHOWING USAGE OF SOME BASIC FUNCTIONS: INT, MOD,
RND, LOCATE, LEN, VAL, STR$, RIGHT$, MID$
INT Functions
It takes a numeric value as its argument and returns its value after truncating the decimal part.
The value returned is always smaller than the number provided as the argument. For example,
10 Y= INT(13.2)
20 X= 15.6
30 Y= INT(X)
Example 1
Two numbers A and B are given. To find the higher number between them:
Program 1
10 INPUT "HIGHER NO"; A
20 INPUT "SMALLER NO ";B
30 LET C = A/B
40 IF INT(C)= C THEN PRINT “ HIGHER NUMBER=“; A
50 END
This shows the use of the INT function.
Example 2
Write a program to find whether any year of the current century is a leap year or not.
80
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Program 2
10 REM ** PROGRAM TO FIND WHETHER THE YEAR IS A LEAP YEAR OR
15 REM NOT **
20 PRINT "ENTER THE YEAR"
30 PRINT
50 INPUT YEAR
60 LET Y1 =INT(YEAR/4)
70 LET Y2 =YEAR/4
80 IF Y1 =Y2 THEN 110
90 PRINT YEAR "IS NOT A LEAP YEAR"
100 GO TO 120
110 PRINT YEAR; "IS A LEAP YEAR"
120 END
(A) Suppose we input year as 1988, then line number 60, we compute Y1 as 497 and also line
number 70 gives Y2 as 497. Thus line number 80 gives Y1=Y2 and so the control is transferred
to 110.
(B) Suppose we input year as 1989. The line number 60, we compute Y1 as 497. In line
number 70, we get Y2 as 497.25. Thus in line number 80 Y1 is not equal to Y2, therefore control
passes to 90.
MOD FUNCTION
Program 3
10 INPUT C, D
20 LET X= C MOD D
30 PRINT X
40 END
The MOD function determines the remainder on dividing a number by another. For example, 9
MOD 2 will give 1.
Program 4
10 LET C= INT (RND*80)+1
20 LET R= INT( RND*25)+1
30 LOCATE R, C : PRINT "*"
40 GO TO 10
50 END
RND*80 and RND*25 generates random numbers between 0 to80 and 0 to25 respectively. Thus,
in line number 10,20 C is assigned the integer value of RND*80 plus 1 and R is assigned the
81
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
value RND*25 plus I respectively. The LOCATE clause followed by R,C followed by PRINT "*",
prints a "*'in the Rth row an Cth column.
Example
10 LET C$ = "BEAUTIFUL"
20 LET C = LEN (C$)
30 PRINT C
40 END
Output is 9 (as there are 9 characters in the word BEAUTIFUL. Note that the function LEN
returns a numeric constant.
VAL(X$) function returns a numeric constant equivalent to the value of the number represented
by the string X$. This string X$ should consist of all digits.
Example
10 LET X$= "12345"
20 LET Y = VAL(X$)
30 PRINT Y
40 END
Example
10 LET Y =7384
20 LET X$=STR$(Y)
30 PRINT X$
40 END
The output will be “7384”. The numeric value of Y is converted to string in line number 20, i.e. X$
= “7384”
Left String
LEFT$ (X$,Y) Returns the left most Y characters from the string X$
Example 1
10 LET X$ = "MATHEMATICS"
20 PRINT LEFT$ (X$, 4)
30 END
The output will be MATH
82
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Example 2
10 LET C$ ="INFORMATICS"
20 LET D$ = LEFTS(C$,6)
30 PRINT D$
40 END
Right string
RIGHT$(Y$,X) returns the rightmost X characters from the string Y$
Example 3
10 LET X$ = "PORTBLANK"
20 PRINT RIGHT$(X$,5)
30 END
Example 4
10 LET A$ = "MANAGED"
20 LET B$ = RIGHT$ (A$,4)
30 PRINT B$
40 END
Middle String
MID$(X$,X,Y) Returns a sub string of X$ starting at the character position X from the left and
containing Y characters.
Example 5
10 LET X$ = "MANHATTAN"
20 PRINT MID$(X$,4,3)
30 END
EXAMPLE PROGRAMS
Problem 1
Write a program to invert TAERG to GREAT.
83
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Program 1
5 LET L$ = “ ”
10 LET C$ = "TAERG"
15 L = LEN(C$)
20 FOR X = L TO 1 STEP -1
30 LET L$ = L$ +MID$(C$,X,1)
40 NEXT X
50 PRINT L$
60 END
Output GREAT
Problem 2
Write a program to give the word GRAPEFRUIT and FRUITGRAPE when GRAPE and are
separately. Given
Program 2
10 LET F$ = "GRAPE"
20 LET B$ = "FRUIT"
30 LET C$ = F$ +B$
40 PRINT C$
50 LET A$ = B$ +F$
60 PRINT A$
70 END
Line 40 prints GRAPEFRUIT
Line 60 prints FRUITGRAPE
Problem 3
The prices of different articles are stored in a one-dimensional table, there product code is also
given as:
Price in Rs. 20 15 16 18 14
Product Code 1 2 3 4 5
Let us assume that product code and quantity sold for an article is inputted through keyboard.
Write a program to calculate and print the cost of sale along with product code and quantity sold.
Terminate the procedure when the product code is out of range.
Program 3
10 DIM P (5)
20 FOR C = 1 TO 5
30 READ P(C)
40 NEXT C
50 DATA 20,15,16,18,14
60 INPUT "PRODUCT CODE"; C
84
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
70 IF C<1 OR C>5 THEN END
80 INPUT "QUANTITY SOLD"; Q
90 LET S = Q*P(C)
100 PRINT "PRODUCT CODE"; C ; "QUANTITY SOLD "; Q; COST OF SALE" ; S
110 GO TO 60
Line number 70 contains END.
Problem 4
A set of given numbers are there. Write a program to arrange them in descending order.
Program 4
10 REM PROGRAM TO ARRANGE THE GIVEN NUMBERS IN DESCENDING
ORDER
15 DIM X (25)
20 INPUT "HOW MANY NUMBERS ARE THERE",N
50 FOR I = 1 TO N
60 READ X (I)
65 NEXT I
70 PRINT "ORIGINAL ORDER IS:"
80 FOR I = 1 TO N
90 PRINT X(I) ;
100 NEXT I
110 PRINT "NUMBERS IN DECREASING ORDER"
120 FOR I = 1 TO N-1
130 FOR J= 1 TO N-1
140 IF A (J)>=A (J+1) THEN 180
150 TEMP= A (J)
160 A (J)= A (J+1)
170 A (J+1) =TEMP
180 NEXT J
190 NEXT I
200 FOR I = 1 TO N
210 PRINT A (I);
220 NEXT I
230 END
Problem 5
From the word "MAIDAMS" write the message "MADAM IS MAD"
Program 5
10 LET A$ = "MAIDAMS'
20 PRINT LEFT$(A$, 2)+MID$(A$,4,3); MID$(A$,3,1)+
RIGHT$(A$, 1);LEFT$(A$,2)+MID$(A$,4,1)
30 END
85
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Problem 6
Write a program to print the Prime Numbers between any two numbers A (say 1) and B (say
100).
Program 6
10 INPUT “TWO NUMBERS”; A,B
20 FOR N= A TO B STEP 1
30 IF N MOD 2= 0 OR N<= 1 THEN GO TO 80
40 FOR X=3 TO SQR(N) STEP 2
50 IF N MOD X =0 THEN 80
60 NEXT X
70 PRINT N; “IS THE PRIME NO”
80 NEXT N
90 END
Explanation
In the line number 30, N MOD 2 is same as MOD(N,2) it gives the remainder of N/2, similarly in
line number 50,N MOD X means remainder of N/X.
Activities/Assessments:
2. If A$ = "TO ERR IS HUMAN" B$ = "TO FORGIVE DIVINE", find the values of following
functions:
(a) LEFT$(A$,2)
(b) MID$(A$, 2, 3)
(c) RIGHT$ (B$, 4)
(d) A$ +" " +B$
(e) MID$ (A$,4, 3) + MID$ (B$,5,2)
Read:
Computer
Programming - Quick Guide - Tutorialspoint.pdf
References:
https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm
87
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM