You are on page 1of 96

Republic of the Philippines

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES


OFFICE OF THE VICE PRESIDENT FOR BRANCHES AND
EXTENSIONS
MARAGONDON BRANCH

INSTRUCTIONAL MATERIALS

IN

CMPE 20022
COMPUTER PROGRAMMING

Compiled by: Checked by:

Virgilio R. Cuajunco, Jr. Assoc. Prof. Ayreenlee E. Resus


Faculty Chairman
Committee on Writing Instructional
Materials

Date: _________________ Date: ___________________

Approved by:

Dr. Agnes Y. Gonzaga Assoc. Prof. Denise A. Abril


Head, Academic Programs Director

Date: _________________ Date: __________________


INTRODUCTION

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!

THE POLYTECHNIC UNIVERSITY OF THE PHILIPPINES

VISION

PUP: The National Polytechnic University

MISSION

Ensuring inclusive and equitable quality education and promoting lifelong learning
opportunities through a re-engineered polytechnic university by committing to:

 provide democratized access to educational opportunities for the holistic development of


individuals with global perspective

 offer industry-oriented curricula that produce highly-skilled professionals with managerial


and technical capabilities and a strong sense of public service for nation building

 embed a culture of research and innovation

 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

 establish a strong presence and impact in the international academic community

PHILOSOPHY

As a state university, the Polytechnic University of the Philippines believes that:

 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

Pillar 1:  Dynamic, Transformational, and Responsible Leadership


Pillar 2: Responsive and Innovative Curricula and Instruction
Pillar 3:  Enabling and Productive Learning Environment
Pillar 4:  Holistic Student Development and Engagement
Pillar 5:  Empowered Faculty Members and Employees
Pillar 6: Vigorous Research Production and Utilization
Pillar 7:  Global Academic Standards and Excellence
Pillar 8: Synergistic, Productive, Strategic Networks and Partnerships
Pillar 9: Active and Sustained Stakeholders’ Engagement
Pillar 10: Sustainable Social Development Programs and Projects

SHARED VALUES AND PRINCIPLES

 Integrity and Accountability


 Nationalism
 Spirituality
 Passion for Learning and Innovation
 Inclusivity
 Respect for Human Rights and The Environment
 Excellence
 Democracy

ii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
MARAGONDON BRANCH

GOALS

 Quality and excellent graduates


 Empowered faculty members
 Relevant curricula
 Efficient administration
 Development – oriented researches
 State-of-the-art physical facilities and laboratories
 Profitable income – generating programs
 Innovative instruction
 ICT – driven library
 Strong local and international linkages

PROGRAM OBJECTIVES

The College of Engineering aims to:


1. Strengthen the Engineering program consistent with global trends;
1. Develop faculty as competent mentors and quality researchers, through advanced study
and other facets of continuing professional education;
2. Develop critical thinking and communication skills of students, giving emphasis to research
and extension services;
3. Equip graduates with appropriate knowledge and technical skills, imbued with desirable
work attitude and moral values through enhanced teaching/learning process by using multi-
media facilities on top of traditional methods;
4. Create a conducive teaching and learning atmosphere with emphasis to faculty and
students’ growth and academic freedom;
5. Establish network with educational institution industry, GO’s and NGO’s, local and
international which could serve as:
a. funding sources and/or partners of researches;
b. sources of new techniques;
c. centers for faculty and student exchange program and On the Job Training; and
d. grantees of scholarship/additional facilities

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

COURSE TITLE : COMPUTER PROGRAMMING


COURSE CODE : CMPE 20022
COURSE CREDIT : 2(0 lecture/2 laboratory) units
PRE-REQUISITE : NONE

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.

Institutional Program outcomes Course outcomes


learning
outcomes
1. Creative and Strengthen the Engineering program consistent Create programs on their own using their
Critical Thinking with global trends logical thinking based on the basic ideas,
concepts, and data presented
2. Effective Develop faculty as competent mentors and Present and interpret accurate, precise,
Communication quality researchers, through advanced study reliable, relevant and computer programs.
and other facets of continuing professional
education
3. Strong Service Create a conducive teaching and learning Apply critical thinking in the analysis of the
Orientation atmosphere with emphasis to faculty and computer programs
students’ growth and academic freedom
4. Passion to Life- Develop critical thinking and communication Generate specific solution to programming
Long Learning skills of students, giving emphasis to research cases.
and extension services Conduct action research on sufficiency of
reporting to meet the needs of a potential
client.
5. Sense of Equip graduates with appropriate knowledge Analyze existing government computer
Nationalism and and technical skills, imbued with desirable work programs and develop a better program for
Global attitude and moral values through enhanced specific functionality.
Responsiveness teaching/learning process by using multi-media
facilities on top of traditional methods
6. Community Establish network with educational institution Be involved in community extension services

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

The course requirements are as follows:

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.

Note: Some activities will be rated using the Rubrics.

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

First semester Class (18 weeks)

Week Topic Learning Outcomes Methodology Resources Assessment


Understand the
Orientation and
mission, vision, goals
Discussion.
and objectives of the
Review of the
University.
Orientation of syllabus,
University’s explanation of
Understand all the
vision, mission, learning activities PUP Student
policies and in-house
1 goals and and assessment. Handbook None
classroom
objectives. Explanation of Course Syllabus
management of the
course
professor.
requirements and
methods of
Acquire the relation of
evaluating student
the subject to their
performance
course and ultimately
Apply steps in program Lecture
Seatwork /
Programming development. Study group
Homework
2-4 Concepts  Design algorithms. Think aloud
Examination
modeling
Design algorithms to
solve problems. Lecture Seatwork /
Predict the results Demonstration Homework
Basic Program when an expression is Study group Examination
5-6
Structure evaluated. Work along Hands-on/
Distinguishes exercise laboratory
assignment, input, and activities
output functions.
7-8 I/O and Program Use single, two-way Lecture Hands-on/
Control Statement and multi-way Demonstration laboratory
1. I/O Statements selection in an Study group activities
Assigned Reading Problem
2. Using algorithm.
Work along Solving /
Conditional exercise Case
Constructs Analysis
Written
vi
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Examination
MIDTERM
9
EXAMINATION
Apply loop constructs Hands-
Lecture
on/laboratory
I/O and Program to indicate repetitive demonstration
activities
Control Statement tasks. Work along
10-11 Results of
exercise
3. Using Looping program
Problem solving
Constructs simulation
Inquiry based
Programming
laboratory work
Exercises
Use arrays to Lecture
Handling of
demonstration Assignment
Arrays, Functions implement sort and
Inquiry based Hands-on
12-13 and Sub-Routine search algorithms laboratory work Quiz
Small Group
1. Arrays
Assignments
Discuss the different Hands-
mathematical function; on/laboratory
Lecture
activities
demonstration
Explain purpose of Results of
Individual/Group
using global and local program
tutorial
2. Functions and simulation
14-15 variables Inquiry based
Sub-Routine Programming
laboratory work
Exercises
Small Group
Problem
Assignments/Proj
Solving /
ect
Case
Analysis
Identify the different Lecture
string and character demonstration
Hands-
functions used in Individual/Group
on/laboratory
tutorial
3. Strings BASIC activities
16-17 Inquiry based
Statements Assignment
laboratory work
Quiz
Small Group
Assignments/Proj
ect
FINAL
18
EXAMINATION

REFERENCES

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

vii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
TABLE OF CONTENTS

Topic Page

Introduction
Orientation

Lesson 1 Programming Concepts 1


Unit 1 Overview of Computer Hardware and Software 1
Unit 2 Flowcharting 10

Lesson 2 Basic Program Structure 18


Unit 1 Elements of Basic Program 18
Unit 2 Operators Expression 24

Lesson 3 I/O and Program Control Statement 29


Unit 1 I/O Statements 29
Unit 2 Using Conditional Constructs 42
Unit 3 Using Loop Constructs 53

Lesson 4 Handling of Arrays, Functions and Sub-Routine 64


Unit 1 Arrays 64
Unit 2 Functions and Sub-routine 73
Unit 3 Strings Statements 79

viii
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Lesson 1 - Programming Concepts

Unit 1 Major hardware components of a computer system

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:

After successful completion of this lesson, you should be able to:

1. define a computer
2. identify characteristics of computer

3. Understand computer programs and what they do.


4. Understand the computer programming basics and environment

Course Materials:

BASIC CONCEPTS

WHAT IS A COMPUTER?

Computer is an electronic device. As mentioned in the introduction it can do arithmetic


calculations faster. But as you will see later it does much more than that. It can be compared to a
magic box, which serves different purpose to different people. For a common man computer is
simply a calculator, which works automatic and quite fast. For a person who knows much about
it, computer is a machine capable of solving problems and manipulating data. It accepts data,
processes the data by doing some mathematical and logical operations and gives us the desired
output.

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.

Introduction to Computer Program

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.

Introduction to Computer Programming

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

Uses of Computer Programs

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

From programming point of view, an algorithm is a step-by-step procedure to resolve any


problem. An algorithm is an effective method expressed as a finite set of well-defined
instructions.
Thus, a computer programmer lists down all the steps required to resolve a problem before
writing the actual code. Following is a simple example of an algorithm to find out the largest
number from a given list of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Largest = L1
3. Take next number Li from the list and do the following
4. If Largest is less than Li
5. Largest = Li
6. If Li is last number from the list then
7. Print value stored in Largest and come out
8. Else repeat same process starting from step 3

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.

Computer Programming - Basics


We assume you are well aware of English Language, which is a well-known Human Interface
Language. English has a predefined grammar, which needs to be followed to write English
statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English,
Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs,
propositions, and conjunctions, etc.

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.

Computer Programming - Environment


Though Environment Setup is not an element of any Programming Language, it is the first step
to be followed before setting on to write a program.
When we say Environment Setup, it simply implies a base on top of which we can do our
programming. Thus, we need to have the required software setup, i.e., installation on our PC

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 −

 A working Internet connection to connect to the Internet


 A Web browser such as Internet Explorer, Chrome, Safari, etc.

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.

 A text editor to create computer programs.


 A compiler to compile the programs into binary format.

 An interpreter to execute the programs directly.

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

 Basic Programming Notes/Lectures

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:

At the end of this lesson, you will be able to understand:


 the meaning of flowchart
 the basic parts of the flowchart such as flowchart symbols and the flow lines
connecting these symbols.
 the advantages and limitations of flowchart

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.

GUIDELINES FOR DRAWING A FLOWCHART


Flowcharts are usually drawn using some standard symbols; however, some special symbols can
also be developed when required. Some standard symbols, which are frequently required for
flowcharting many computer programs are shown in Figure below:

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

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

Figure Flowchart Symbols

The following are some guidelines in flowcharting:


(a) In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
(b) The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
(c) The usual direction of the flow of a procedure or system is from left to right or top to
bottom.

(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.

Yes <0 >0

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.

This is top secret data

(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.

ADVANTAGES OF USING FLOWCHARTS


The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem are analyzed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which
is needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part
LIMITATIONS OF USING FLOWCHARTS
1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes
a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.
13
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
EXAMPLES ON FLOWCHARTING
Now we shall present few examples on flowcharting for proper understanding of this technique.
This will help in student in program development process at a later stage.

Example 1 Draw a flowchart to find the sum of first 50 natural numbers.


START

SUM = 0

N=0

N=N+1

SUM = SUM + N

IS PRINT SUM
NO YES
N=50?

Sum of first 50 natural numbers END

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
? ? ?

YES NO YES YES

NO NO

PRINT C PRINT C PRINT A


PRINT B

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

M=M+1 I PRINT F END


S
YES
M
Fig 25.4 =
Flowchart for computing factorial N
N
?
Example 4
A company’s salesmen are selling toothpaste and tooth powder. The company having 50
salesmen gives 10% commission on the sale of toothpaste and 20% commission on tooth
powder.
Draw a flowchart to compute and print the total sale and the total commission for each salesman.

Answer: The required flowchart is shown in Fig 25.5

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

Flowchart for Computing Commission on Different Items


Example 5
Modify the flowchart in Example 4 to print the following heading.
Salesman No Total Sale Total commission
Under these heading, write the values of these variables for the 50 salesmen. At the end, the
totals of the entire sale and the entire commission should also be printed out.

Answer: The required flowchart is shown in Figure


Note:
16
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
TS = Total sales
TC = Total commission

Flowchart for writing proper heading and its contents


Activities/Assessments:

1. Fill in the blank.


(i) A program flowchart indicates the_________ to be per formed and the __________ in which

they occur.
(ii) A program flowchart is generally read from _____________ to ________________

(iii) Flowcharting symbols are connected together by means of ___________________

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:

1. Draw a flowchart to read a number N and print all its divisors.


2. Draw a flowchart for computing the sum of the digits of any given number
3. Draw a flowchart to find the sum of given N numbers.
4. Draw a flowchart to computer the sum of squares of integers from 1 to 50
5. Draw a flowchart to arrange the given data in an ascending order.

References:

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

Lesson 2 - Basic Program Structure

Unit 1 ELEMENTS OF BASIC STRUCTURE

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:

At the end of this lesson, you should be able:


 to know how to construct constants, variables in BASIC language and
expression using mathematical, relational and logical operators.
 learn the structure and essential elements of BASIC.
 use some elementary BASIC commands in small programs.

Course Materials:

BASIC AS A PROGRAMMING LANGUAGE


Basic is quite simple language and easy to understand. It is becoming more popular as an
interactive language. Now we shall discuss various features of this language.

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.

The advantages of BASIC can be summed up as follows:


 BASIC is easy to learn and fun to practice. It may be called a `People's
language'.

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.

ELEMENTARY BASIC STATEMENTS


In the program, you came across their important BASIC commands or keywords. These are
REM, PRINT and END. We will briefly discuss REM and END here. The PRINT will be discussed
in greater details in subsequent lessons. Presently for the purpose of understanding, you may
take PRINT, as an output instruction. The output may be meant for the terminal (as in this case)
or it may be directed to a disk file. What is important, is to remember, that in BASIC, print does
not necessarily mean a print out on a paper; it may mean display on the terminal or write on a
disk file also.

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:

10 REM : This is my first program


20 PRINT
30 PRINT "WELCOME TO NATIONAL OPEN SCHOOL"
40 END

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.

THE CHARACTER SET


BASIC has the character set consisting of the following elements:
(a) Alphabets: A, B, C, ----. Z
(b) Digits: 0,1,2, ----, 9 and
(c) Special characters: + - * / ( ) . , $ ; : = > < " ^
The symbol ^ (caret) is used to denote exponentiation operator, the symbol * (asterisk) is used to
denote multiplication and the other symbols have their usual meanings. In addition these, blank
space denoted by the symbol b is also regarded as a character.

CONSTANTS AND VARIABLES


A quantity in a computer program which does not change its value during the execution of the
program is called a constant and the quantity which may change its values during the execution
of the program is called a variable. BASIC allows the following constants:
 Numeric constant
 String constant

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.

It is also important to keep in mind that


 BASIC does not distinguish between an integer and a fraction.
 Commands are not allowed in a numeric constant
 The limit on the number of digits that can be used varies from computer to computer.
Normally, a numeric constant can have up to a maximum of eight digits.

A string constant consists of a sequence of characters. It must be enclosed by a quotation mark.


This may contain blank space as a character but it should not include the quotation mark. String
constants are used to represent non-numeric quantities such as names, addresses, etc. For
example, "PANKAJ GOEL", "SUM = Rs 75", "162" are a few valid string constants.
In BASIC, variables are also of two types. They are
 Numeric variable
 String variable

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 -

2. Which of the following BASIC strings are correct?


(a) January 26, 1997
(b) Sixty-two
23
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(c) 5121942
(d) 100 - 40 =60
(e) SUM "10"

3. Write the following as ordinary numbers:


(a) 1.23E6
(b) 1.5E - 5
(c) - 3E + 2
(d) 5.865696 E + 6
(e) - 1.2 E -2

References:

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

Unit 2 Operators Expressions

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:

After successful completion of this lesson, you should be able:

1. to write in computer expression an algebraic expression


2. to write Boolean expression and truth table

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

Algebraic Expression BASIC Equivalent


25
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
2A+B 2*A+B
A(B+C) A*(B+C)
A B
.......... .......... .......... ....( A  B ) /(C  D)
CD
B2-4AC B^2-4*A*C

RELATIONAL OR LOGICAL EXPRESSIONS

A relational expression is formed by using any of the following relational operators:

Relational Operator Meaning


= Equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
<> Not equal to

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

LIBRARY FUNCTIONS IN BASIC

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.

To find the logarithm of  by using LOG function you write

10 LET Y = LOG (X),

The variable Y will store the LOG value of X.

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.

Function Name Purpose Example


SIN Sine Calculate the Sine value SIN(X)
of an angle (in radians) SIN(44/7)
LOG LOG Calculate the natural LOG(X)
logarithm of a number LOG(100)
SQR Square root Calculate the square SQR(A)
root of a number SQR(100)

(c) The function name is to be written exactly as given. No deviation is permitted.

(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:

1. Evaluate the following BASIC expressions:


(a) 3 * 4/2 ^ 3 + 1

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

3. Define BASIC language along with its features.


4. Describe briefly the structure of BASIC language.
5. Differentiate between
(a) Numeric and String constant
(b) Arithmetical and Relational Expression
6. Write down the hierarchy of operations in Arithmetic Expression.
7. Define history of BASIC language briefly.

References:

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

Lesson 3 - I/O and Program Control Statement

Unit 1 INPUT-OUTPUT STATEMENTS

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:

At the end of this lesson, you should be able to:


 understand clearly the use of INPUT/OUTPUT statements such as LET, READ-DATA,
INPUT, PRINT, PRINT USING etc.
 learn the use of LOOPING and CONTROL statements.
 develop BASIC programs using the various basic commands offered by the language

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.

Getting Data into Memory

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:

Line number LET (variable name)=(Constants or Variables or expression)

Example of LET statement

10 LET X =5.32 ---> This is numeric constant

20 LET A = 6+9/3.2--> This is an arithmetic expression


30
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
30 LET Y = X+A --> This is also an arithmetic expression

40 LET I = 2-->numeric constant

50 LET I =I+Y -->I and Y are variable names

60 LET A$ = "NEW DELHI”--> String variable

70 LET F$ = "99983" -->String variable

80 LET A = B--> numeric variable

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.

Memory location Memory location

A B

Execution of line 15 10 Not known

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.

Location A Location B Location C

Line number 15 10 Not known Not known

Line number 25 10 5 Not known

Line number 35 10 5 15

INPUT Statement

Syntax

Line number INPUT Variable,List...

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....

Line number DATA Constant, List....

Example of a READ....DATA Statement

1 REM PROGRAM EXPLAINING READ....DATA STATEMENT


5 READ X2,Y,Z1,K
9 READ A,B3, C4, L
22 DATA 8,9,13,15,16,51,30,92
30 END

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

Value Pointer Variable


122 <--- X1
-35 <--- Y1
49 <--- Z1
-101 <--- N
33
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
-691 <--- M
81 <--- L
8 <--- K
10 <--- A
-5 <--- X
5 <--- Y

Now look at the following some examples where all the programs do exactly the same work.

(a) 10 DATA "RAMA","DELHI",100,200,300


20 READ A$,B$,A, B, C
30 - - - - -
40 -----
--------------
80 END

(b) 10 READ A$,B$


20 READ A,B,C
30 ------
40 - - - - - -
60 DATA "RAMA","DELHI"
70 DATA 100,200,300
100 END
(c) 10 DATA "RAMA","DELHI"
20 DATA 100
30 DATA 200
40 DATA 300
50 READ A$,B$
60 READ A,B,C
-------------
100 END

(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.

So we note that for READ....DATA statement we should follow the following

 There could be any number of READ and DATA statements.


 As many variables are read by READ statement, at least the same number of values

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

Line number RESTORE

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)

(Position of pointer before execution of RESTORE statement)

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

The RESTORE statement can be used in the following forms also:

Statement number RESTORE *

and

Statement number RESTORE $

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.

For example, if a BASIC program contains the following statements,

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.

Consider another 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

Line number PRINT (Variable) separator (variable) separator or item......

The separation may be comma (,) or semicolon (;)

The Semicolon (;) Control

Program

10 LET S =1175.50

20 PRINT "TOTAL SALARY =";S; " RUPEES"

30 END

The output of the program 1 will be as

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,

The Comma (,) Control

100 PRINT "NUM","TEMP","SIZE", REMARK"

110 PRINT 65,-15.56,36,34

These two lines will be printed as follows

1 17 33 49 65 85

Zone 1 Zone 2 Zone 3 Zone 4 Zone 5

NUM TEMP SIZE REMARK

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.

Print Using Statement

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:

100 PRINT USING "##. ##"; A,B,C,

Line number PRINT USING Format String Numeric Variables

The format string "##. ##", which a numeric field containing a decimal point with not more than
two digits on each side.

What will be the output of the following program?

10 LET A =17.32
20 LET B = -5.38
30 LET C =40
40 PRINT USING "##. ##",A,B,C,
50 END

OUTPUT

17.32 -5.38 40.00

If string values are used instead of numeric values, the format string for PRINT USING will be as
follows:

100 PRINT USING "!!!!!!" ; N$

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.

Note: Some computers use # for presenting a character.

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

(b) 100 PRINT USING ">!!!!!!";N$ gives output as

(> character is used for the right justification of a string.)

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.

With the same explanation

100 PRINT USING “<!!!!!!”; N$ gives output FROG b b

(< is for left justified), Left justified space filled to right.

Note: b is used as space character.

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:

Line number PRINT TAB (N); X

Where N is a positive number, a variable or an expression having positive value and X shows
output data

The execution of TAB function is explained below:-

(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.

The backward movement of the printer head is not allowed.

39
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
For example, consider the statement

10 PRINT TAB (25); "DINESH"; TAB(20); "RAJESH"

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

10 PRINT TAB (25); "DINESH"; "RAJESH"

Consider another example, where TAB function is ignored

20 PRINT "10.3", TAB (10); "15.6"

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.

PROGRAM CONTROL STATEMENTS # # THEIR SYNTAX AND USE

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

1. Fill in the blanks

(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

 Basic Programming Notes/Lectures

Unit 2 Using Conditional Constructs

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:

After successful completion of this lesson, you should be able to:


1. Branch programming in certain condition
2. Use if-then else and on goto statements

Course Materials:

The Branching Statement IF... THEN


The IF...THEN is a decision making statement, depending upon the decision, it can change the
order of execution.
It helps the computer to check whether a relation is TRUE or FALSE.
Syntax: Line number IF (relational expression) THEN n where n is a line number or an instruction
itself.
If the relation expression is true then n will be executed otherwise the statement following this
IF...THEN statement will be executed.

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.

The Branching Statement IF...THEN...ELSE

Another important statement is IF ...THEN...ELSE.


Syntax:
Line number IF (condition or relational expression)
THEN (line number or Instruction)
ELSE (line number or Instruction)
The IF...THEN...ELSE statement is a decision making statement as it decides the path of the
program. It helps in making comparisons and testing whether a condition is true or not.
IF is always followed by a valid BASIC condition or expression. If the condition is found true then
the line number or Instruction after THEN is performed otherwise line number or instruction after
ELSE is performed.

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:

50 PRINT "A IS THE LARGEST NUMBER"


55 GO TO 80
60 PRINT "B IS THE LARGEST NUMBER"
65 GO TO 80

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;

IF (Condition 1 or Relational expression) AND (Condition 2 or Relational expression) THEN


(Instruction 1) ELSE (Instruction 2)

Like AND another logical operator is OR.

Syntax: for IF…. THEN...ELSE with OR is:


IF (Condition 1 or Relational expression) OR (condition 2 or Relational expression)
THEN (Instruction 1) ELSE (Instruction 2)

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 −

Assume given marks are x for a student:

If given marks are more than 95, then


Student is brilliant

If given marks are less than 30, then


Student is poor

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;

if( x > 95) {

printf( "Student is brilliant\n");


}
if( x < 30) {

printf( "Student is poor\n");


}
if( x < 95 && x > 30 ) {

printf( "Student is average\n");


}
}
When the above program is executed, it produces the following result −
Student is average
The above program uses if conditional statements. Here, the first if statement checks
whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is
true, then the conditional body is entered to execute the given statements. Here we have only
one printf() statement to print a remark about the student.

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) {

/* Statement(s) will execute if the boolean expression is true */


} else {

/* Statement(s) will execute if the boolean expression is false */


}
The above syntax can be represented in the form of a flow diagram as shown below −

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( x > 95) {

printf( "Student is brilliant\n");


} else {
printf( "Student is not brilliant\n");
}
}

When the above program is executed, it produces the following result −


Student is not brilliant

if...elseif...else statement

An if statement can be followed by an optional else if...else statement, which is very useful to


test various conditions.

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.

The syntax of an if...else if...else statement in C programming language is –

if(boolean_expression 1) {

/* Executes when the boolean expression 1 is true */


}
else if( boolean_expression 2) {

/* Executes when the boolean expression 2 is true */


}
else if( boolean_expression 3) {

/* Executes when the boolean expression 3 is true */


} else {

/* Executes when the none of the above condition is true */


}

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;

if( x > 95) {


printf( "Student is brilliant\n");
}
else if( x < 30) {
printf( "Student is poor\n");
}
else if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
}

When the above program is executed, it produces the following result −


Student is average

The Switch Statement


A switch statement is an alternative of if statements which allows a variable to be tested for
equality against a list of values. Each value is called a case, and the variable being switched on
is checked for each switch case. It has the following syntax −
switch(expression){
case ONE :
statement(s);
break;
case TWO:
statement(s);
break;
......

default :
statement(s);
}

The expression used in a switch statement must give an integer value, which will be compared


for equality with different cases given. Wherever an expression value matches with a case
value, the body of that case will be executed and finally, the switch will be terminated using
a break statement. If no break statements are provided, then the computer continues executing
other statements available below to the matched case. If none of the cases matches, then the
default case body is executed.

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");
}
}

When the above program is executed, it produces the following result −


Two

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.

public class DemoJava {


public static void main(String []args) {
int x = 45;

if( x > 95) {


System.out.println( "Student is brilliant");
}
else if( x < 30) {
System.out.println( "Student is poor");
}
else if( x < 95 && x > 30 ) {
System.out.println( "Student is average");
}
}
}

When the above program is executed, it produces the following result −

Student is average

Decisions in Python

Following is the equivalent program written in Python. Python provides if, if...else, if...elif...else,


and switch statements. Here, you must note that Python does not make use of curly braces for
conditional body, instead it simply identifies the body of the block using indentation of the
statements.

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"

print "The end"

When the above program is executed, it produces the following result −


Student is average
The end

References:

https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

Basic Programming Notes/Lectures

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:

After successful completion of this lesson, you should learn:

1. To use iteration process in solving probl;ems


2. Use For to next statement

Course Materials:

The Looping Statement FOR-TO...NEXT


A loop is built up by FOR-TO and ended by NEXT.

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 Multiple Branching Statement ON... GOTO

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.

If ON is followed by an expression by an expression then it is evaluated and truncated to an


integer value. Control is transferred in the same manner as discussed above.
If the integer value is less than or more than number of line numbers present in the list then an
"OUT OF RANGE" error message will be given by the computer.

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

1 control is transferred to 30,


2 control is transferred to 40,
3 control is transferred to 50,
4 control is transferred to 60

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.

The while Loop


A while loop available in C Programming language has the following syntax −
while ( condition ) {
/*....while loop body ....*/
}
The above code can be represented in the form of a flow diagram as shown below −

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 do...while Loop


A while loop checks a given condition before it executes any statements given in the body part.
C programming provides another form of loop, called do...while that allows to execute a loop
body before checking a given condition. It has the following syntax −
do {
/*....do...while loop body ....*/
}
while ( condition );

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!

The break statement

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!

The continue statement

The continue statement in C programming language works somewhat like the break statement.


Instead of forcing termination, continue forces the next iteration of the loop to take place,
skipping any code in between. The syntax for a continue statement in C is as follows −
continue;
A continue statement can be represented in the form of a flow diagram as shown below –

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 );
}

When the above program is executed, it produces the following result −


Hello, World!
Hello, World!
Hello, World!
Hello, World!

Loops in Java

Following is the equivalent program written in Java that too supports while and do...while loops.


The following program prints Hello, World! five times as we did in the case of C Programming −
You can try to execute the following program to see the output, which must be identical to the
result generated by the above example.

public class DemoJava {


public static void main(String []args) {
int i = 0;

while ( i < 5 ) {
System.out.println("Hello, World!");
i = i + 1;
}
}
}

The break and continue statements in Java programming work quite the same way as they


work in C programming.

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

while (i < 5):


print "Hello, World!"
i=i+1
print "Loop ends"

When the above program is executed, it produces the following result −


Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

Loop ends

The break and continue statements in Python work quite the same way as they do in C


programming.

Activities/Assessments:

1. Write a LET statement for each of the following:


(a) To assign the value 5.2 to the variable A
(b) To assign the string PENTIUM-SYSTEM TO the variable B$
(c) To assign the value of the variable C to the variable D
(d) To increase the value of the variable E by 1
(e) To assign the value equal to three times the value of the variable P to the variable Q

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

3. Give the output of the following short program


63
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
10 PRINT "PANKAJ" , "GOEL"
20 PRINT "PANKAJ" ; "GOEL"
30 PRINT "PANKAJ",, "GOEL"

4. Give the output of the following short program


10 LET A = 40
20 LET B = 50
30 LET C = 60
40 LET D = A+B+C
50 PRINT “A= A”; A “B = B”; B “C=”; C, “D=”; D
60 END

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

 Basic Programming Notes/Lectures

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:

HANDLING LISTS AND TABLES (ARRAYS) IN BASIC


In all our programs so far, a single variable (one storage location in internal memory) has been
associated with each variable name. In this lesson, we will discuss the concept of an array: a
collection of variables, all of which are referenced by the same name. We will discuss one-
dimensional arrays (lists) and two-dimensional arrays (tables), concentrating on the former. Each
item of data in an array does not have a unique variable name, on the other hand, a group of
similar data is given one name. The smallest component of an array is called an element of the
array.

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.

In the memory it is stored as,


M(I) Cells Quantities

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

Let us go back to the above example.


M is an array of 5 numbers 10,12,42,91,7, where under the array name M the five different
elements M(1),M(2), M(3), M(4), M(5), are given one subscript I. This M(I), with a single subscript
I, is an example of a one-dimensional array. Let us study a practical example of one-dimensional
array.

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

Line number 90 due to line number 80 and 100 will print


60
45.5
32.6
19.5
52
49
53.75
29
43
38.6

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:

FORD MARUTI AMBASSADOR FIAT STANDARD VAUXHAL L

We can write a program as follows:

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.

The program for adding all the 10 numbers.

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

The DIM Statement


When subscripted variables are used in a program, certain information about them must be
supplied to the computer before it is used. These are:
(a) Which variables are subscripted?
(b) What is the maximum size for each subscript?

DIM is the short form of DIMENSION.

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

Double-Subscripts or two-dimensional arrays


A subscripted variable name in BASIC can have up to three subscripts. The use of two subscripts
has very wide applications, especially manipulation of tables or any such things, which has rows
and columns both in it.
Example: Represent subscripted variable or two-dimensional array having name TABLE(I.,J)
where I indicates row and J indicates column.
Where, TABLE (I,J) = 2 4 8 10
1 3 5 7
3 7 13 17

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

TABLE(1,1) TABLE(1,2) TABLE(1,3) TABLE(1,4)


2 ---------> 4 --------> 8 ----------> 10
TABLE(2,1) TABLE(2,2) TABLE(2,3) TABLE(2,4)
1 ---------> 3 --------> 5 ----------> 7
TABLE(3,1) TABLE(3,2) TABLE(3,3) TABLE(3,4)
3 ---------> 7 --------> 13 ----------> 17

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.

HARIOM DINESH RAJESH PANKAJ


BIMLA UPMA SANJU ANAMIKA

The program is as follows:

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.

2. Correct the errors in each of the following program segments:


(a) 10 FOR K = 1 TO 5
20 FOR J = 1 TO K
30 PRINT K + J
40 NEXT K
50 NEXT J

(b) 10 LET S = 0
20 FOR I = 1 TO 10
30 LET S = S + I
40 PRINT S
50 NEXT K

3. What is the output of each of the following program segments?


(a) 10 FOR I = 7 TO 10 STEP 2
20 PRINT I;
30 NEXT I
40 PRINT I
50 END

(b) 10 FOR I = 1TO 10


20 IF I = 5 THEN 40
30 PRINT I + 1
40 NEXT I
50 END

4. Determine whether each of the following statements is true or false.


(a) Array of string data and array of numeric data can be declared in the same DIM
statement.
(b) All elements of an array must be of either string type or numeric type.
(c) One and two-dimensional arrays cannot be declared in the same DIM statement.

5. A two-dimensional array FAX has two rows and four columns


5 10 15 20

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 ?

6. What is displayed when the following program segment is executed?


10 DIM A (2,3)
20 FOR I = 1 TO 2
30 FOR J = 1TO3
40 LET A(I,J) = I+J+1
50 NEXT J
60 NEXT I
70 PRINT A(1,2); A(2,1); A(2,2)
80 END

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.

8. Write a BASIC program to arrange the following numbers in an ascending order:


-71, -20, 14, 0, 5

References:

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

Unit 2 Functions and Sub-routine


73
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Overview:

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:

FUNCTION AND SUBROUTINE

Defining a function---the DEF statement


To avoid repeated programming of the same set of calculations, the programmer would like to
write his or her own functions, which are similar to the Library functions. It may so happen that a
particular calculation or a set of calculations occurs more than once in the program. If the
calculation can be defined by a single statement then we use the function statement DEF FN.

Syntax: line number DEF FNV (a) = expression

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.

Defining a subroutine -The GOSUB and RETURN statements


A subroutine is a collection of statements belonging to a process, which requires to be repeated
very frequently in the program. A subroutine consists of set of program statements that may be
used repeatedly at different places throughout the main program. In the main program the
subroutines are called at different places using GOSUB statement.

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:

Line no ON Numeric variable GOSUB


Or
Numeric expression (Line number of sub-routine 1, sub. 2,
sub .3….)
Program 2
10 INPUT A,B
20 INPUT "1-ADD, 2-SUB, 3-MUL, 4-DIV"; N
30 ON N GOSUB 50, 60, 70, 80
40 END (To make the program repeat we should add GOTO 10)
50 PRINT A+B : RETURN
60 PRINT A-B : RETURN
70 PRINT A*B : RETURN
80 PRINT A/B : RETURN

Note: To make the program repeat, we should add GOTO 10 at line 35

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?

2. What is displayed when each of the following program segments is run?


(a) 10 GOSUB 400
20 GOSUB 500
30 PRINT "ONE"
40 END
400 PRINT "TWO"
410 RETURN
500 PRINT "THREE"
510 RETURN

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

 Basic Programming Notes/Lectures

79
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Unit 3 Strings Statements

Overview:

Strings in programming are represented as arrays of characters. Computer programming


simplified the assignment and printing of strings. Most of the programming languages provide
built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a
string, you can extract sub-strings from a string.

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)

Statement 10 will return Y = 13 and


Statement 30 will return Y = 15.

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.

THE RND, LOCATE function


RND generates random numbers between 0 and 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.

THE LEN, VAL, STR$ function


LEN is used to count the number of character in a string. It takes a string as an argument and
counts every character including a blank.

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

Output of this program, on execution, will be 12345.


STR$(Y)
This is the reverse operation of VAL. The value of Y here is converted into a string literal. Y can
be a numeric constant, variable or expression.

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”

String Processing in BASIC


Following are the few functions, which operate on string variables and help in string processing.

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

Output will be INFORM.

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

Output will be BLANK.

Example 4
10 LET A$ = "MANAGED"
20 LET B$ = RIGHT$ (A$,4)
30 PRINT B$
40 END

Output will be AGED.

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

Output will be HAT.

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

Line number 20 can be put in two consecutive PRINT statement also.

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:

1. (a) What is the use of an INT function?


(b) What would be the value of X in the following program segments?
(i) C$ = "AVAILABLE"
X = LEN(C$)
(ii) C$ = "899"
X = VAL(C$)

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)

3. Write a BASIC program to run up the following series


(a) 1,3,5,7, 9 ………………100
(b) 2,4,6,8,10………………100
(c) 1,4,9,16,25………………100
(d) 1,8,27,64,125……………1000
86
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
4. What will be the output of the following programs?

(a) 10 FOR I = 1 TO 3 (b) 10 FOR I = 1 TO 5


20 FOR J = 1 TO 5 20 READ K
30 PRINT I, J, I+J 30 PRINT I ;
40 IF J = 3 THEN 100 40 FOR J = 1 TO K
50 PRINT I, J , I*J 50 PRINT ““;
60 PRINT I+J, I-J 60 NEXT J
70 PRINT 70 PRINT
100 NEXT J 80 NEXT I
110 NEXT I 90 DATA 5,9,3,2,6
120 END 100 END

5. Write a program to invert LOOHCS to SCHOOL.

6. Write a program to write


PANKAJ KUMAR GOEL as P.K. GOEL.

7. Write a program to write your own address 10 times on the screen.

Read:

Computer
Programming - Quick Guide - Tutorialspoint.pdf

References:

 https://www.tutorialspoint.com/computer_programming/computer_programming_numbers.htm

 Basic Programming Notes/Lectures

87
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM

You might also like