Cs1123 2 comp_prog

51
Introduction to Programming (CS1123) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad Fall 2013

Transcript of Cs1123 2 comp_prog

Page 1: Cs1123 2 comp_prog

Introduction to Programming(CS1123)

By

Dr. Muhammad Aleem,

Department of Computer Science, Mohammad Ali Jinnah University, Islamabad

Fall 2013

Page 2: Cs1123 2 comp_prog

What is a Computer?

• A computer is a electro-mechanical device that works semi-automatically to process input data according to the stored set of instructions and produces output or resultant data.

A Computer System

Instructions

DataResults

Page 3: Cs1123 2 comp_prog

Components of a Computer System

Main Memory

CPU

Arithmetic and Logic Unit

Control Unit

Computer

Peripheral Devices / Connected devices

Keyboard Mouse Display CD Rom Hard Disk

Page 4: Cs1123 2 comp_prog

Computer Instructions and Programs

• Instruction: A computer instruction is a command or directive given to a computer to perform specific task.

Examples: Add 2 and 5, Print “Hello World”

• Program: A program is sequence of instructions written in programming language that directs a computer to solve a problem

Examples: Draw a square, etc.

Page 5: Cs1123 2 comp_prog

Computer Instructions and Programs

• Program “Draw a square”

1 – Draw a vertical line of length n inches

2 – Draw a horizontal line of n inches

3– Draw a vertical line of length n inches

4 – Draw a horizontal line of n inches

Page 6: Cs1123 2 comp_prog

Computer Software System

Operating Systems (Windows, Linux, MAC, Solaris)

Compilers / Libraries (C++, C, Java)

Application Programs(.cpp, .c, .java,)

Computer Hardware

Page 7: Cs1123 2 comp_prog

Programming Languages

• Classification of programming languages:

1. Machine language

2. Low-level languages

3. High-level languages

Page 8: Cs1123 2 comp_prog

1. Machine level languages

• A computer understands only sequence of bits or 1’s and 0’s (the smallest piece of information)

• A computer program can be written using machine languages (01001101010010010….)

• Very fast execution

• Very difficult to write and debug

• Machine specific (different codes on different machines)

Page 9: Cs1123 2 comp_prog

2. Low level languages

• English encrypted words instead of codes (1’s and 0’s)

• More understandable (for humans)

• Example: Assembly language

• Requires: “Translation” from Assembly code to Machine code

compare: cmpl #oxa,n cgt

end_of_loop acddl #0x1,nend_of_loop:

10010101010011011110010110010100010101011101001001101001101110111101100101010101

Assembler

Assembly Code Machine Code

Page 10: Cs1123 2 comp_prog

3. High level languages

• Mostly machine independent

• Close to natural language (English like language keywords)

• Easy to write and understand programs

• Easy to debug and maintain code

• Requires compilers to translate to machine code

• Slower than low-level languages

Page 11: Cs1123 2 comp_prog

3. High level languages

• Some Popular High-Level languages– COBOL (COmmon Business Oriented Language)– FORTRAN (FORmula TRANslation) – BASIC (Beginner All-purpose Symbolic Instructional Code) – Pascal (named for Blaise Pascal) – Ada (named for Ada Lovelace) – C (whose developer designed B first) – Visual Basic (Basic-like visual language by Microsoft) – C++ (an object-oriented language, based on C)– Java

Page 12: Cs1123 2 comp_prog

Programming Paradigms

• Programming paradigm is the fundamental style of computer programming

1. Imperative2. Functional 3. Logical4. Object Oriented

Page 13: Cs1123 2 comp_prog

Imperative Paradigm

• Machine based modes (Sequence of steps required to compute)

• Statements executed sequentially step-wise

• Emphasis on How is to compute

• How to obtain the required results or output

• Example languages: C, Pascal, Ada, etc.

Page 14: Cs1123 2 comp_prog

Imperative Paradigm Languages

Page 15: Cs1123 2 comp_prog

Functional/Logical Paradigm

• Specify what is to be computed using programming abstractions.

• Responsibility of a programmer is to specify What is to compute

• How to compute is implementation dependent and is managed by language compiler

• Example languages: Lisp, Scheme, Erlang, Haskell, Scala etc.

Page 16: Cs1123 2 comp_prog

Object-Oriented Paradigm

• Programming with Abstract Data Types, to model real world

• Basic Program Unit: Class (a programmer defined type)– A entity that contains data and methods which work

on the data

• Basic Run-time Unit: Object– Instance of a class during execution

Page 17: Cs1123 2 comp_prog

Problem Solving Steps

1. Understand the problem2. Plan the logic3. Code the program4. Test the program5. Deploy the program into production

Page 18: Cs1123 2 comp_prog

1. Understanding the Problem

• Problems are often described in natural language like English.

• Users may not be able to specify needs well, and the needs may changing frequently

• Identify the requirements1. Inputs or given data-items

2. Required output(s) or desired results

3. Indirect inputs (may not be given directly, you have to calculate or assume)

Page 19: Cs1123 2 comp_prog

1. Understanding the Problem

– Example: Calculate the area of a circle having the radius of 3 cm• Inputs: – Radius=3

• Output: – Area

• Indirect Inputs: – Pi=3.14

– Area = 3.14 * (3*3) = 28.27

Page 20: Cs1123 2 comp_prog

2. Plan the Logic

• Identify/Outline small steps in sequence, to achieve the goal (or desired results)

• Tools such as flowcharts and pseudocode can be used:1. Flowchart: a pictorial representation of the logic

steps2. Pseudocode: English-like representation of the logic

• Walk through the logic before coding

Page 21: Cs1123 2 comp_prog

3. Code the Program

• Code the program:

– Select the programming language

–Write the program instructions in the selected programming language

–Use the compiler software to translate the program into machine understandable code or executable file

– Syntax errors (Error in program instructions) are identified by the compiler during compilation and can be corrected.

Page 22: Cs1123 2 comp_prog

4. Test the Program

• Testing the program–Execute it with sample data and check the

results

– Identify logic errors if any (undesired results or output) and correct them

–Choose test data carefully to exercise all branches of the logic (Important)

Page 23: Cs1123 2 comp_prog

5. Deploy the Program

• Putting the program into production–Do this after testing is complete and all known

errors have been corrected

Page 24: Cs1123 2 comp_prog

Introduction to Pseudocode

• One of the popular representation based on natural language

• Widely used– Easy to read and write–Allow the programmer to concentrate on the

logic of the problem

• Structured in English language (Syntax/grammar)

Page 25: Cs1123 2 comp_prog

What is Pseudocode (continued...)

• English like statements

• Each instruction is written on a separate line

• Keywords and indentation are used to signify particular control structures.

• Written from top to bottom, with only one entry and one exit

• Groups of statements may be formed into modules

Page 26: Cs1123 2 comp_prog

Some Basic Constructs

• Print Output is to be sent to the Printer

• Write Output is to be written to a file

• Display Output is to be written to the screen

• Prompt required before an input instruction Get, causes the message to be sent to the screen

• Compute /Calculate Calculation performed by computer

• Calculation operations: +, -, *, /, ()

Page 27: Cs1123 2 comp_prog

Some Basic Constructs

• Set Used to set inital value, E.g., Set Marks to 0

• = Place values from right hand-side item to left hand side

E.g., Marks = 67

• Save Save the variable in file or disk E.g., Save Marks

Page 28: Cs1123 2 comp_prog

Comparison/Selection

IF student_Marks are above 50 THENResult = “Pass“

ELSEResult = “Fail“ENDIF

• Making decision by comparing values• • Keywords used: • IF, THEN, ELSE

IF student_Marks are above 50 THENResult = “Pass“

ELSEResult = “Fail“

ENDIF

Page 29: Cs1123 2 comp_prog

Comparison/Selection

CASE of <condition-variable> Case <valueA>

Do Step1 Case <valueB>

Do Step2 Case <valueC>

Do Step3ENDCASE

• Case Strtucture Multiple banching based on value of condition

• Three keywords used: • CASE of, Case, ENDCASE

Page 30: Cs1123 2 comp_prog

Comparison/Selection

• Case Strtucture Example...

Page 31: Cs1123 2 comp_prog

Repeat a group of Statements

DOWHILE student_total < 50Read student recordPrint student nameAdd 1 to student_total

ENDDO

• Repeating set of instruction base on some condition

• Keyword used: • DOWHILE, ENDDO

Page 32: Cs1123 2 comp_prog

Example Pseudocode Program

• A program is required to read three numbers, add them together and print their total.

Inputc Processing Output

Number1Number2Number3

total

Page 33: Cs1123 2 comp_prog

Solution Algorithm

Add_three_numbersSet total to 0

Read number1 Read number2 Read number3Total = number1 + number2 + number3Print total

END

Page 34: Cs1123 2 comp_prog

Repeat Until (Loop)• Repeat-Until statement (loop)

REPEAT Do StepA Do StepB

UNTIL conditionN is True

- What is the Difference between (While & Repeat) ?

Example:…

Page 35: Cs1123 2 comp_prog

Flowcharts• “A graphic representation of a sequence of

operations to represent a computer program”

• Flowcharts show the sequence of instructions in a single program or subroutine.

Page 36: Cs1123 2 comp_prog

A Flowchart• A Flowchart– Shows logic of an algorithm or problem– Shows individual steps and their interconnections– E.g., control flow from one action to the next

Page 37: Cs1123 2 comp_prog

Name Symbol Description

Oval Beginning or End of the Program

Parallelogram Input / Output Operations

Rectangle Processing for example, Addition, Multiplication, Division, etc.

Diamond Denotes a Decision (or branching) for example IF-Then-Else

Arrow Denotes the Direction of logic flow

Flowchart Symbols

Page 38: Cs1123 2 comp_prog

Example 1

Step 1: Input M1,M2,M3,M4Step 2: GRADE = (M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then

Print “FAIL” else

Print “PASS” endif

START

InputM1,M2,M3,M4

GRADE(M1+M2+M3+M4)/4

ISGRADE<50

STOP

YN

Print“FAIL”

Print“PASS”

Page 39: Cs1123 2 comp_prog

Example 2• Write an algorithm and draw a flowchart to

convert the length in feet to centimeter.

Page 40: Cs1123 2 comp_prog

Example 2

Algorithm • Step 1: Read Lft• Step 2: Lcm = Lft x 30 • Step 3: Print Lcm

Flowchart

START

Read Lft

Lcm = Lft x 30

STOP

Print LCM

Page 41: Cs1123 2 comp_prog

Example 3• Write an algorithm and draw a flowchart that will read

the two sides of a rectangle and calculate its area.

Page 42: Cs1123 2 comp_prog

Example 3

Algorithm • Step 1: Read W,L• Step 2: A = L x W • Step 3: Print A

START

ReadW, L

A L x W

STOP

PrintA

Page 43: Cs1123 2 comp_prog

DECISION STRUCTURES • The expression A>B is a logical expression

• It describes a condition we want to test

• if A>B is true (if A is greater than B) we take the action on left

• Print the value of A

• if A>B is false (if A is not greater than B) we take the action on right

• Print the value of B

Page 44: Cs1123 2 comp_prog

IF–THEN–ELSE STRUCTURE

• The algorithm for the flowchart is as follows:If A>B then

print AElse

print Bendif

isA>B

Y N

Print A Print B

Page 45: Cs1123 2 comp_prog

• Multiple branching based on a single condition

CASE STRUCTURE

CASE Condition

Do Step A Do Step B Do Step C Do Step D

Page 46: Cs1123 2 comp_prog

Relational / Logical Operators

Relational Operators

Operator Description> Greater than

< Less than

= Equal to

Greater than or equal to Less than or equal to

Not equal to

Page 47: Cs1123 2 comp_prog

Example 4• Write an algorithm that reads two values, finds largest

value and then prints the largest value.

ALGORITHMStep 1: Read VALUE1, VALUE2Step 2: if (VALUE1 > VALUE2) then

MAX VALUE1else

MAX VALUE2endif

Step 3: Print “The largest value is”, MAX

-- DRAW the Flow Chart for the Program

Page 48: Cs1123 2 comp_prog

Selection Structure• A Selection structure can be based on

1. Dual-Alternative (two code paths)2. Single Alternative (one code path)

isA>B

Y N

Print A Print B

Dual Alternative Example

Page 49: Cs1123 2 comp_prog

Selection Structure• Single Alternative Example

Pseudocode: IF GPA is greater than 2.0 ThenPrint “Promoted ”

End IF

GPA > 2.0

N Y

Print “Promoted”

Page 50: Cs1123 2 comp_prog

Loop Structure• Repetition (WHILE structure)– Repeats a set of actions based on the answer to a

question/condition pseudocode: DoWHILE <Some-True-Condition>

Do SomethingENDDO

Page 51: Cs1123 2 comp_prog

Loop Structure• REPEAT-UNTIL structure– Repeats a set of actions until a condition remains True

– pseudocode: REPEAT Do-Something

UNTIL <Some True Condition>