8

COMPUTER PROGRAMMING FUNDAMENTALS

Contents

  • Program development life cycle—Problem analysis, program design, program development, program documentation and maintenance
  • Algorithm
  • Control structures—Sequential, selection (branch or conditional), iterative (loop)
  • Flowchart—Flowchart symbols, preparing a flowchart
  • Pseudo code—Preparing a pseudo code • Difference between algorithm, flowchart and pseudo code
  • Programming paradigms
    • Structured programming—Procedural programming, modular programming
    • Object-oriented programming—Class, object, abstraction, encapsulation, inheritance, polymorphism (static binding, dynamic binding)
    • Aspect-oriented programming—Crosscutting concerns, aspect
  • Characteristics of a good program

Why this chapter

A program is a set of instructions written for performing a specific task. However, writing a good program is not a straightforward task. For writing a program, we have to follow the program development life cycle which includes choosing a programming paradigm, and selecting a computer programming language in which to write the program. With practice, you can easily acquire the skill of program writing. The purpose of this chapter is to introduce you to the fundamentals of Computer Programming.

8.1 INTRODUCTION

Computer is an electronic device that accepts data, processes it, and generates the relevant output. It can perform both simple and complex tasks with very high speed and accuracy. However, a computer cannot perform any task—simple or complex, of its own. Computers need to be instructed about “how” the task is to be performed. The set of instructions that instruct the computer about the way the task is to be performed is called a program. A program is required for processing all kind of tasks—simple tasks like addition of two numbers, and complex tasks like gaming etc.

In this chapter, we will discuss the steps that are followed while writing a computer program. A brief description of different programming constructs is also presented. We will also discuss the characteristics of a good program.

8.2 PROGRAM DEVELOPMENT LIFE CYCLE

As stated earlier, a program is needed to instruct the computer about the way a task is to be performed. The instructions in a program have three essential parts:

  1. Instructions to accept the input data that needs to be processed,
  2. Instructions that will act upon the input data and process it, and
  3. Instructions to provide the output to user

The instructions in a program are defined in a specific sequence. Writing a computer program is not a straightforward task. A person who writes the program (computer programmer) has to follow the Program Development Life Cycle.

Let’s now discuss the steps that are followed by the programmer for writing a program:

  • Problem Analysis—The programmer first understands the problem to be solved. The programmer determines the various ways in which the problem can be solved, and decides upon a single solution which will be followed to solve the problem.
  • Program Design—The selected solution is represented in a form, so that it can be coded. This requires three steps—
    • An algorithm is written, which is an English-like explanation of the solution.
    • A flowchart is drawn, which is a diagrammatic representation of the solution. The solution is represented diagrammatically, for easy understanding and clarity.
    • A pseudo code is written for the selected solution. Pseudo code uses the structured programming constructs. The pseudo code becomes an input to the next phase.
  • Program Development
    • The computer programming languages are of different kinds—low-level languages, and high- level languages like C, C++ and Java. The pseudo code is coded using a suitable programming language.
    • The coded pseudo code or program is compiled for any syntax errors. Syntax errors arise due to the incorrect use of programming language or due to the grammatical errors with respect to the programming language used. During compilation, the syntax errors, if any, are removed.
    • The successfully compiled program is now ready for execution.
    • The executed program generates the output result, which may be correct or incorrect. The program is tested with various inputs, to see that it generates the desired results. If incorrect results are displayed, then the program has semantic error (logical error). The semantic errors are removed from the program to get the correct results.
    • The successfully tested program is ready for use and is installed on the user’s machine.
  • Program Documentation and Maintenance—The program is properly documented, so that later on, anyone can use it and understand its working. Any changes made to the program, after installation, forms part of the maintenance of program. The program may require updating, fixing of errors etc. during the maintenance phase.

Table 8.1 summarises the steps of the program development cycle.

Program Analysis • Understand the problem
• Have multiple solutions
• Select a solution
Program Design • Write Algorithm
• Write Flowchart
•Write Pseudo code
Program Development • Choose a programming language
• Write the program by converting the pseudo code, and then using the programming language.
• Compile the program and remove syntax errors, if any
• Execute the program.
• Test the program. Check the output results with different inputs. If the output is incorrect, modify the program to get correct results.
• Install the tested program on the user’s computer.
Program Documentation and maintenance • Document the program, for later use.
• Maintain the program for updating, removing errors, changing requirements etc.

Table 8.1 Program development life cycle

8.3 ALGORITHM

Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a task. Algorithm is an English-like representation of the logic which is used to solve the problem. It is a step- by-step procedure for solving a task or a problem. The steps must be ordered, unambiguous and finite in number.

For accomplishing a particular task, different algorithms can be written. The different algorithms differ in their requirements of time and space. The programmer selects the best-suited algorithm for the given task to be solved.

Let’s now look at two simple algorithms to find the greatest among three numbers, as follows:

Algorithm to find the greatest among three numbers

ALGORITHM 1.

Step 1: Start

Step 2: Read the three numbers A, B, C

Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.

Step 4: Compare A and C. If A is greater, output “A is greatest” else output “C is greatest”. Perform step 6.

Step 5: Compare B and C. If B is greater, output “B is greatest” else output “C is greatest”.

Step 6: Stop

ALGORITHM 2.

Step 7: Start

Step 8: Read the three numbers A, B, C

Step 9: Compare A and B. If A is greater, store A in MAX, else store B in MAX.

Step 10: Compare MAX and C. If MAX is greater, output “MAX is greatest” else output “C is greatest”.

Step 11: Stop

Both the algorithms accomplish the same goal, but in different ways. The programmer selects the algorithm based on the advantages and disadvantages of each algorithm. For example, the first algorithm has more number of comparisons, whereas in the second algorithm an additional variable MAX is required.

8.4 CONTROL STRUCTURES

The logic of a program may not always be a linear sequence of statements to be executed in that order. The logic of the program may require execution of a statement based on a decision. It may repetitively execute a set of statements unless some condition is met. Control structures specify the statements to be executed and the order of execution of statements.

Flowchart and Pseudo code use control structures for representation. There are three kinds of control structures:

  • Sequential—instructions are executed in linear order
  • Selection (branch or conditional)—it asks a true/false question and then selects the next instruction based on the answer
  • Iterative (loop)—it repeats the execution of a block of instructions.

The flowchart and the pseudo code control structures are explained in their respective sections.

8.5 FLOWCHART

A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is drawn using boxes of different shapes with lines connecting them to show the flow of control. The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form. There is a famous saying S“A photograph is equivalent to thousand wordsS”. The same can be said of flowchart. The logic of the program is communicated in a much better way using a flowchart. Since flowchart is a diagrammatic representation, it forms a common medium of communication.

8.5.1 Flowchart Symbols

A flowchart is drawn using different kinds of symbols. A symbol used in a flowchart is for a specific purpose. Figure 8.1 shows the different symbols of the flowchart along with their names. The flowchart symbols are available in most word processors including MS-WORD, facilitating the programmer to draw a flowchart on the computer using the word processor.

A single line description of the flowchart symbols is given in Table 8.2.

8.5.2 Preparing a Flowchart

A flowchart may be simple or complex. The most common symbols that are used to draw a flowchart are—Process, Decision, Data, Terminator, Connector and Flow lines. While drawing a flowchart, some rules need to be followed—(1) A flowchart should have a start and end, (2) The direction of flow in a flowchart must be from top to bottom and left to right, and (3) The relevant symbols must be used while drawing a flowchart. While preparing the flowchart, the sequence, selection or iterative structures may be used wherever required. Figure 8.2 shows the sequence, selection and iteration structures.

Figure 8.1 Flowchart symbols (available for use in MS-WORD)

Process—operation or action step Decision—decision or a branch
Alternate Process—alternate to normal process Data—I/O to or from a process
Document—a document Manual Input—Data entry from a form
Multi document—more than one document Manual Operation—operation to be done manually
Preparation—set-up process Connector—join flow lines
Punched Tape—I/O from punched tape Off page connector—continue on another page
Collate—organize in a format Summing Junction—Logical AND
Merge—merge in a predefined order OR—Logical OR
Sort—sort in some order Sequential Access storage—stored on magnetic tape
Display—display output Stored Data—general data storage
Predefined process—process previously specified Magnetic Disk—I/O from magnetic disk
Internal Storage—stored in memory Direct access storage—storing on hard disk
Termination—start or stop point Flow lines—indicates direction of flow
Delay—wait Extract—split process
  Card—I/O from a punched card

Table 8.2 Description of flowchart symbols

Figure 8.2 Control structures in flowchart

We see that in a sequence, the steps are executed in linear order one after the other. In a selection operation, the step to be executed next is based on a decision taken. If the condition is true (yes) a different path is followed than if the condition evaluates to false (no). In case of iterative operation, a condition is checked. Based upon the result of this conditional check, true or false, different paths are followed. Either the next step in the sequence is executed or the control goes back to one of the already executed steps to make a loop.

Here, we will illustrate the method to draw flowchart, by discussing three different examples. To draw the flowcharts, relevant boxes are used and are connected via flow lines. The flowchart for the examples is shown in Figure 8.3.

Figure 8.3 Examples of flowchart

  • The first flowchart computes the product of any two numbers and gives the result. The flowchart is a simple sequence of steps to be performed in a sequential order.
  • The second flowchart compares three numbers and finds the maximum of the three numbers. This flowchart uses selection. In this flowchart, decision is taken based upon a condition, which decides the next path to be followed, i.e. If A is greater than B then the true (Yes) path is followed else the false (No) path is followed. Another decision is again made while comparing MAX with C.
  • The third flowchart finds the sum of first 100 integers. Here, iteration (loop) is performed so that some steps are executed repetitively until they fulfill some condition to exit from the repetition. In the decision box, the value of I is compared with 100. If it is false (No), a loop is created which breaks when the condition becomes true (Yes).

Flowcharts have their own benefits; however, they have some limitations too. A complex and long flowchart may run into multiple pages, which becomes difficult to understand and follow. Moreover, updating a flowchart with the changing requirements is a challenging job.

8.6 PSEUDO CODE

Pseudo code consists of short, readable and formally-styled English language used for explaining an algorithm. Pseudo code does not include details like variable declarations, subroutines etc. Pseudo code is a short-hand way of describing a computer program. Using pseudo code, it is easier for a programmer or a non-programmer to understand the general working of the program, since it is not based on any programming language. It is used to give a sketch of the structure of the program, before the actual coding. It uses the structured constructs of the programming language but is not machine-readable. Pseudo code cannot be compiled or executed. Thus, no standard for the syntax of pseudo code exists. For writing the pseudo code, the programmer is not required to know the programming language in which the pseudo code will be implemented later.

8.6.1 Preparing a Pseudo Code

  • Pseudo code is written using structured English.
  • In a pseudo code, some terms are commonly used to represent the various actions. For example, for inputting data the terms may be (INPUT, GET, READ), for outputting data (OUTPUT, PRINT, DISPLAY), for calculations (COMPUTE, CALCULATE), for incrementing (INCREMENT), in addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction, and initialization, respectively.
  • The control structures—sequence, selection, and iteration are also used while writing the pseudo code.
  • Figure 8.4 shows the different pseudo code structures. The sequence structure is simply a sequence of steps to be executed in linear order. There are two main selection constructs—if-statement and case statement. In the if-statement, if the condition is true then the THEN part is executed otherwise the ELSE part is executed. There can be variations of the if-statement also, like there may not be any ELSE part or there may be nested ifs. The case statement is used where there are a number of conditions to be checked. In a case statement, depending on the value of the expression, one of the conditions is true, for which the corresponding statements are executed. If no match for the expression occurs, then the OTHERS option which is also the default option, is executed.
  • WHILE and DO-WHILE are the two iterative statements. The WHILE loop and the DO- WHILE loop, both execute while the condition is true. However, in a WHILE loop the condition is checked at the start of the loop, whereas, in a DO-WHILE loop the condition is checked at the end of the loop. So the DO-WHILE loop executes at least once even if the condition is false when the loop is entered.

Figure 8.4 Control structures for pseudo code

In Figure 8.5, the pseudo code is written for the same three tasks for which the flowchart was shown in the previous section. The three tasks are—(i) compute the product of any two numbers, (ii) find the maximum of any three numbers, and (iii) find the sum of first 100 integers.

Figure 8.5 Examples of pseudo code

A pseudo code is easily translated into a programming language. But, as there are no defined standards for writing a pseudo code, programmers may use their own style for writing the pseudo code, which can be easily understood. Generally, programmers prefer to write pseudo code instead of flowcharts.

Difference between Algorithm, Flowchart, and Pseudo Code: An algorithm is a sequence of instructions used to solve a particular problem. Flowchart and Pseudo code are tools to document and represent the algorithm. In other words, an algorithm can be represented using a flowchart or a pseudo code. Flowchart is a graphical representation of the algorithm. Pseudo code is a readable, formally styled English like language representation of the algorithm. Both flowchart and pseudo code use structured constructs of the programming language for representation. The user does not require the knowledge of a programming language to write or understand a flowchart or a pseudo code.

8.7 PROGRAMMING PARADIGMS

The word “paradigm” means an example that serves as a pattern or a model. Programming paradigms are the different patterns and models for writing a program. The programming paradigms may differ in terms of the basic idea which relates to the program computation. Broadly, programming paradigms can be classified as follows:

  1. Structured Programming,
  2. Object-Oriented Programming (OOP), and
  3. Aspect-Oriented Programming (AOP). AOP is a new programming paradigm.

Earlier, the unstructured style of programming was used, where all actions of a small and simple program were defined within a single program only. It is difficult to write and understand a long and complex program using unstructured programming. The unstructured style of programming is not followed nowadays.

8.7.1 Structured Programming

  • Structured programming involves building of programs using small modules. The modules are easy to read and write.
  • In structured programming, the problem to be solved is broken down into small tasks that can be written independently. Once written, the small tasks are combined together to form the complete task.
  • Structured programming can be performed in two ways—Procedural Programming and Modular Programming (Figure 8.6).
  • Procedural Programming requires a given task to be divided into smaller procedures, functions or subroutines. A procedural program is largely a single file consisting of many procedures and functions and a function named main (). A procedure or function performs a specific task. The function main () integrates the procedures and functions by making calls to them, in an order that implements the functionality of the program. When a procedure or function is called, the execution control jumps to the called procedure or function, the procedure or function is executed, and after execution the control comes back to the calling procedure or function.
  • Modular Programming requires breaking down of a program into a group of files, where each file consists of a program that can be executed independently. In a modular program, the problem is divided into different independent but related tasks. For each identified task, a separate program (module) is written, which is a program file that can be executed independently. The different files of the program are integrated using a main program file. The main program file invokes the other files in an order that fulfills the functionality of the problem.

    Figure 8.6 Structured programming

  • In structured programming, the approach to develop the software is process-centric or procedural. The software is divided into procedures or modules, based on the overall functionality of the software. As a result, the procedures and modules become tightly interwoven and interdependent. Thus, they are not re-usable.
  • C, COBOL and Pascal are examples of structured programming languages.

8.7.2 Object-Oriented Programming (OOP)

OOP focuses on developing the software based on their component objects. The components interact with each other to provide the functionality of the software. Object-oriented programming differs from procedural programming. In OOP the software is broken into components not based on their functionality, but based on the components or parts of the software. Each component consists of data and the methods that operate on the data. The components are complete by themselves and are re-usable. The terms that are commonly associated with object-oriented programming are as follows:

  • Class is the basic building block in object-oriented programming. A class consists of data attributes and methods that operate on the data defined in the class.
  • Object is a runtime instance of the class. An object has a state, defined behavior and a unique identity. The state of the object is represented by the data defined in the class. The methods defined in the class represent object behavior. A class is a template for a set of objects that share common data attributes and common behavior.
  • Abstraction, Encapsulation, Inheritance and Polymorphism are the unique features of object-oriented software.
  • Abstraction allows dealing with the complexity of the object. Abstraction allows picking out the relevant details of the object, and ignoring the non-essential details. Encapsulation is a way of implementing abstraction.
  • Encapsulation means information hiding. The encapsulation feature of object-oriented software hides the data defined in the class. Encapsulation separates implementation of the class from its interface. The interaction with the class is through the interface provided by the set of methods defined in the class. This separation of interface from its implementation allows changes to be made in the class without affecting its interface.
  • The Inheritance feature of object-oriented software allows a new class, called the derived class, to be derived from an already existing class known as the base class. The derived class (subclass) inherits all data and methods of the base class (super class). It may override some or all of the data and methods of the base class or add its own new data and methods.
  • Polymorphism means, many forms. It refers to an entity changing its form depending on the circumstances. It allows different objects to respond to the same message in different ways. This feature increases the flexibility of the program by allowing the appropriate method to be invoked depending on the object executing the method invocation call.
  • C++ and Java are object-oriented programming languages.

8.7.3 Aspect-Oriented Programming (AOP)

Aspect-oriented programming is a new programming paradigm that handles the crosscutting concerns of the software. The crosscutting concerns are the global concerns like logging, authentication, security, performance, etc., that do not fit into a single module or related modules. In OOP, the business logic or core concern is encapsulated in well-defined classes. However, the code for implementing crosscutting concerns is intertwined with a number of related classes or modules and gets scattered in the different classes of the software.

AOP is a new paradigm that focuses on the issue of handling crosscutting concerns at the programming language level. It helps the programmer in cleanly separating the core concerns and the crosscutting concerns of the software. AOP introduces a new modular unit called “aspect” that encapsulates the functionality of the crosscutting concerns. Aspects of a system are independent elements that can be changed, inserted or removed at compile time, and even reused without affecting the rest of system. Aspects are similar to the classes of object oriented programs; however, they implement the crosscutting concerns. At compilation time, the classes of object oriented programs and the aspects are combined into a final executable form using an “aspect weaver”.

  • AspectJ and AspectC are examples of aspect-oriented programming languages.

After having selected a suitable programming paradigm for the program to be written, the coding of the logic of a program has to be done in a computer programming language. For the purposes of coding, the programmer checks the requirements and suitability of the task, and selects from among the programming languages available for the selected programming paradigm.

Characteristics of a Good Program: A program written using any of the programming language must have certain characteristics, which makes it a good program. Some of the key characteristics of a good program are as follows:

  • The program should be well-written so that it is easily readable and structured.
  • The program should not have hard-coded input values. This implies that it should not be written to work for a particular input value, but must be a general program (also called generic program) that accepts input from the user.
  • The program should also be well-documented so that later the author or any other programmer can understand the program.
  • Since new and better operating systems keep coming up, a program must be designed to be portable, i.e. with minimum dependence on a particular operating system.

A program comprising of the above features is generally characterized as a good program.

SUMMARY
  • Program isaset of instructions that instruct the computer about the way the task is to be performed.
  • Program development life cycle consists of—analyze problem to select a solution, write algorithm, draw flowchart and write pseudo code for the selected solution, write program code in a programming language, remove syntax and semantic errors, and install successfully tested program. Also, document the program to make program maintenance easy.
  • Algorithm is an ordered sequence offinite, well-defined, unambiguous instructions for completing a task.
  • Control structures specify the statements that are to be executed and the order of the statements that have to be executed. Sequential, selection, and iteration are three kinds of control structures.
  • Flowchart is a diagrammatic representation of the logic for solving a task. Flowchart is a tool to document and represent the algorithm. Flowchart is drawn using the flowchart symbols.
  • Pseudo code consists of short, readable and formally-styled English language which is used to explain and represent an algorithm. There is no standard syntax for writing the pseudo code, though some terms are commonly used in a pseudo code.
  • A pseudo code is easily translated into a programming language.
  • In structured programming, the given problem is broken down into smaller tasks based on their functionality. The individual tasks can be written independently, and later combined together to form the complete task. A structured program can be procedural or modular.
  • A procedural program is largely a single file consisting of many procedures and functions.
  • A modular program is a group of files, where each file consists of a program that can be executed independently.
  • In OOP, software is broken into components based on the components of the software. Class is the basic building block. Object is a runtime instance of class. Abstraction, encapsulation, inheritance, and polymorphism are the unique features of object-oriented software.
  • AOP is a new paradigm that focuses on the handling of crosscutting concerns like logging, authentication, security, and performance, at the programming language level. The crosscutting concerns are defined in a new modularization unit called aspect.
  • A good program is readable, structured, generic, well- documented and portable.
KEYWORDS

Abstraction

Iteration

Programming paradigm

Algorithm

Modular Programming

Pseudo code

Aspect

Object

Selection construct

Aspect-Oriented

Object-Oriented

Semantic error

Programming (AOP)

Programming (OOP)

Sequential structure

Class

Polymorphism

Static binding

Control structures

Problem Analysis

Structured Programming

Crosscutting concerns

Procedural Programming

Syntax error

DO-WHILE statement

Program

WHILE statement

Dynamic binding

Program Design

 

Encapsulation

Program Development

 

Flowchart

Program Development Life

 

Flowchart Symbols

Cycle

 

If-Then statement

Program Documentation

 

Inheritance

Program Maintenance

 

QUESTIONS

Section 8.1–8.2

1. Define a program.

2. Explain the program development life cycle in detail.

3. What is the difference between syntax error and semantic error?

4. Define syntax error.

5. Define semantic error.

6. What is the purpose of program maintenance?

Section 8.3–8.4

7. Define algorithm.

8. What are control structures?

9. Name the three kinds of control structures.

10. State the purpose of each of the control structures:

  1. Sequence,
  2. Selection, and
  3. Iteration.

Section 8.5

11. Define flowchart.

12. Draw the flowchart symbol for the following—(i) Process, (ii) Decision, (iii) Document, (iv) Connector, and (v) Magnetic Disk.

13. State the meaning of the following flowchart symbols—(i) Process, (ii) Decision, (iii) Document, (iv) Connector, (v) Magnetic Disk, and (vi) Flow lines.

14. Draw the control structures (Sequence, Selection and Iteration) for the flowchart.

Section 8.6–8.7.3

15. Define pseudo code.

16. Write the pseudo code control structures (sequence, selection, and iteration).

17. What is the difference between WHILE and DO- WHILE statements?

18. Name the different programming paradigms.

19. What is modular programming?

20. What is procedural programming?

21. Name two procedural programming languages.

22. What are the key features of OOP?

23. Define: (i) class, (ii) object, (iii) abstraction, (iv) encapsulation, (v) inheritance, and (vi) polymorphism.

24. How is static binding different from dynamic binding in OOP?

25. Name two object-oriented programming languages.

26. How is AOP different from OOP?

27. Define an aspect.

28. Name two aspect-oriented programming languages.

29. Explain the characteristics of a good program.

Programming Exercise

30. Write the algorithm, draw a flowchart, and write pseudo code for the following:

  1. To find the sum of square root of any three numbers.
  2. To find the sum of first 100 integers.
  3. To find the sum of all even numbers till 100.
  4. To find the sum of all odd numbers till 100.
  5. To find the sum of any five integers.
  6. To find the factorial of a number n. Hint: n! = n(n−1)(n−2)….3.2.1
  7. To find the first n numbers in a Fibonacci series. Hint: f(0) = 0, f(1) = 1, f(n) = f(n−1) + f(n−2)
  8. To find the sum of digits of a number. (For example, for number 345 find 3+4+5)
  9. To check whether a number is prime or not.
  10. To convert the temperature from Fahrenheit to Celsius. Hint: C= (5/9)*(F-32)

Extra Questions

31. Give full form for the following abbreviations:

  1. AOP
  2. OOP

32. Write short notes on:

  1. Program Development Life Cycle
  2. Algorithm
  3. Control structures
  4. Flowchart
  5. Pseudo code
  6. Structured programming
  7. Object-Oriented Programming
  8. Aspect-Oriented Programming
  9. Characteristics of a good program

33. Give differences between the following:

  1. Flowchart and Pseudo code
  2. Algorithm, Flowchart and Pseudo code
  3. Modular Programming and Procedural Programming
  4. Selection and Iteration
  5. OOP and AOP
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233