CMPE 20022 COMPUTER PROGRAMMING ECE Lesson 1

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

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

3
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
from a given starting point. This same sequence could have been given in Spanish, Hindi,
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
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.

6
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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 −

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.

8
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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.

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

9
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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
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


10
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
Computational steps or processing function of a program

Input or output operation

Decision making and branching

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

11
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
(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.

(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.
(i) Ensure that the flowchart has a logical start and finish.
(j) 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

12
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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.

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 N=50? PRINT SUM


NO YES

Sum of first 50 natural numbers END

Fig 2.2 Flowchart for computing the sum of first 50 natural numbers.

13
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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

YES NO YES YES

NO NO

PRINT B PRINT C PRINT C PRINT A

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=F*M

NO
M=M+1 PRINT F END

YES
Fig 25.4 Flowchart for computing factorial N

14
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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

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


15
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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:
TS = Total sales
TC = Total commission

Flowchart for writing proper heading and its contents


16
SUBJECT: CMPE 20022 – COMPUTER PROGRAMMING
PREPARED BY: VIRGILIO R. CUAJUNCO, JR., MEM
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 ___________________

(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

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

You might also like