46
Computer Programming I 1 Lecture 2 Algorithms and Problem Solving

Computer Programming - Lecture 2

Embed Size (px)

Citation preview

Page 1: Computer Programming - Lecture 2

Computer Programming I 1

Lecture 2 Algorithms and Problem Solving

Page 2: Computer Programming - Lecture 2

Computer Programming I 2

Overview

Algorithm Program design Pseudocode Structure diagram Flowcharts Introduction to C++ Testing and debugging Program errors

Page 3: Computer Programming - Lecture 2

Computer Programming I 3

Algorithm

Algorithm A sequence of precise instructions which

leads to a solution

Program An algorithm expressed in a language the

computer can understand

Page 4: Computer Programming - Lecture 2

Computer Programming I 4

Program Design

Programming is a creative process No complete set of rules for creating a program

Program Design Process Problem Solving Phase

• Result is an algorithm that solves the problem

Implementation Phase• Result is the algorithm translated into a programming

language

Page 5: Computer Programming - Lecture 2

Computer Programming I 5

Problem Solving Phase

Be certain the task is completely specified What is the input? What information is in the output? How is the output organized?

Develop the algorithm before implementation Experience shows this saves time in getting your

program to run. Test the algorithm for correctness

Page 6: Computer Programming - Lecture 2

Computer Programming I 6

Implementation Phase

Translate the algorithm into a programming language Easier as you gain experience with the language

Compile the source code Locates errors in using the programming language

Run the program on sample data Verify correctness of results

Results may require modification of the algorithm and program

Page 7: Computer Programming - Lecture 2

Computer Programming I 7

Object Oriented Programming

Abbreviated OOP

Used for many modern programs

Program is viewed as interacting objects Each object contains algorithms to describe

its behavior Program design phase involves designing

objects and their algorithms

Page 8: Computer Programming - Lecture 2

Computer Programming I 8

8

Input Processing Output

Names for our cells

5, 10 15

1) Declare variablesinput_1input_2sum

2) Assign valuesinput_1 = 5input_2 = 10

3) Processsum = input_1 + input_2

The computer (and so C++)provides basic arithmeticoperations. If the operationyou want to use is not provided,you have to compose it.

Sample problemsWrite a program calculating the sum of two numbers

Page 9: Computer Programming - Lecture 2

Computer Programming I 9

There are many models supporting the development of the code. We will see now the same algorithm expressed as:

1)Pseudocode2)Structure diagram3)Flowcharts

and finally in C++.

Write a program calculating the sum of two numbers

Page 10: Computer Programming - Lecture 2

Computer Programming I 10

Pseudocode

Mixture of C++ and ordinary English Allows us to make our algorithm precise

without worrying about the details of C++ syntax

Page 11: Computer Programming - Lecture 2

Computer Programming I 11

PROGRAM Add Two NumbersREAD two numbersADD the numbersWRITE the sum

END PROGRAM

Version 1:PROGRAM Add Two Numbers

READ FirstREAD SecondSum = First + SecondWRITE Sum

END PROGRAM

Version 2:

Write a program calculating the sum of two numbers

Pseudocode

Page 12: Computer Programming - Lecture 2

Computer Programming I 12

Structure Diagram

Helpful to break the algorithm into more manageable pieces

Version 1: PROGRAM Add Two Numbers

READTwo Numbers

ADDTwo Numbers

WRITEThe Sum

Write a program calculating the sum of two numbers

Page 13: Computer Programming - Lecture 2

Computer Programming I 13

Structure Diagram

Version 2: PROGRAM Add Two Numbers

READTwo Numbers

ADDTwo Numbers

WRITEThe Sum

READInput_1

READInput_2

Sum = Input_1 + Input_2

Write a program calculating the sum of two numbers

Page 14: Computer Programming - Lecture 2

Computer Programming I 14

Rules for Structure Diagram

A module which resides above others is referred to as a Calling module

A module which resides below another is referred to as a Called module

A module can be both a calling and called module

A called module can only be called by one calling module

Page 15: Computer Programming - Lecture 2

Computer Programming I 15

Flowchart

Diagram that shows the logical flow of a program Stress on structured programming Useful for planning each operation a program

performs, and in order in which the operations are to occur

By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved

The final visualization can then be easily translated into a program

Page 16: Computer Programming - Lecture 2

Computer Programming I 16

Flowcharting symbols

Input/Output (used for all I/O operations)

Processing (used for all arithmetic and data transfer operations).

Decision (used to test for a condition).

Terminal (used to indicate the beginning and end of a program or module).

Connector (used to indicate the point at which a transfer of control operation occurs).

Predefined (used to indicate the name process of a module to be executed).

Connecting all the symbols and showing the flow

Page 17: Computer Programming - Lecture 2

Computer Programming I 17

READ FirstREAD Second

Sum = First + Second

WRITE Sum

Write a program calculating the sum of two numbers

START

END

Page 18: Computer Programming - Lecture 2

Computer Programming I 18

1) Each symbol denotes a type of operation.

2) A note is written inside each symbol to indicate the specific function to be performed.

3) The symbols are connected by flow-lines.

4) Flowcharts are drawn and read from top to bottom unless a specific condition is met that alters the path.

5) A sequence of operations is performed until a terminal symbol designates the sequence's end or the end of the program.

6) Sometimes several steps or statements are combined in a single processing symbol for ease of reading.

Flowchart Conventions

Page 19: Computer Programming - Lecture 2

Computer Programming I 19

Page 20: Computer Programming - Lecture 2

Computer Programming I 20

start

Input A

Input B

A > B

print Aprint B

end

A flowchart to accept two numbers as input and prints out the maximum

TrueFalse

Page 21: Computer Programming - Lecture 2

Computer Programming I 21

Structured Programming

Structured Programming is a technique using logical control constructs that make programs easier to read, debug, and modify if changes are required.

Sequence Selection Repetition

true false

true

Page 22: Computer Programming - Lecture 2

Computer Programming I 22

Different selection structures

A>10

S1

true false

true false

If a > 10 then do S1

S1 S2

A>10

If a > 10 then do S1 else do S2

truefalse

S2

A>10

If a > 10 then do nothing else do S2

FalseTrue

S1

A<=10

If a <= 10 then do S1

Page 23: Computer Programming - Lecture 2

Computer Programming I 23

Loop structures

A<=10

S1

S2

true

A<=10

S1

S2

true

Repeat

S1

S2

As long as A is Less than or equal to 10 otherwise exit the loop

False

False

While A is less than or equal to 10 repeat

S1

S2

End loop

What is the difference ?

Page 24: Computer Programming - Lecture 2

Computer Programming I 24

Loop example (do..While)Loop example (do..While)

c<=5

Sum = Sum + A

C = C + 1

true

Draw a flowchart to allow the input of 5 numbers and displays out the sum of these numbers

Input A

Start

C = 1

Sum=0

Output Sum

End

False

Assume the numbers given to A are 3,2,4,5,6 in order

C=1Sum = 0

C=1Sum = 0

A=3

C=1Sum = 3

A=3

1

2

3

4

5

6

7

1,2 3 4

C=2Sum = 3

A=3

5

C=2Sum = 3

A=3C <=5 true

6

C=2Sum = 3

A=2

C=2Sum = 5

A=2

3 4

C=3Sum = 5

A=2

5

C=3Sum = 5

A=3C <=5 true

6

C=3Sum = 5

A=4

C=3Sum = 9

A=4

3 4

C=4Sum = 9

A=4

5

Page 25: Computer Programming - Lecture 2

Computer Programming I 25

Loop example (while…)Loop example (while…)

c<=5

Sum = Sum + A

C = C + 1

true

Draw a flowchart to allow the input of 5 numbers and displays out the sum of these numbers

Input A

Start

C = 1

Sum=0

Output Sum

End

False

Assume the numbers given to A are 3,2,4,5,6 in order

C=1

C=1Sum = 0

1

2

3

4

5

6

7

1

2

C=1Sum = 0

C <=5 true

C=1Sum = 3

A=3

C=1Sum = 3

A=3

34

C=2Sum = 3

A=3

5 6

C=2Sum = 3

C <=5 true

C=2Sum = 3

A=2

C=2Sum = 5

A=2

3 4

C=3Sum = 5

A=3

5 6

Page 26: Computer Programming - Lecture 2

Computer Programming I 26

Prime number example flowchart

Pseudocode algorithm to solve this problem:

1. Start

2. Input a number M

3. Set an Index (I) to start from 2

4. Divide the number M by the Index (I) value and store the remainder in R

5. If R is equal to zero then output “Not Prime” and goto to Step 10

6. Increment Index (I) by 1

7. If the Index (I) value is less than the number M go to Step 4

8. Output “Prime”

9. End

R=0?

I = I + 1

True

Input M

Start

I = 2

R=M%I

Output Prime

End

False

I<M?

Output Not Prime

True

False

1

2

3

4

5

6

7

8

9

Page 27: Computer Programming - Lecture 2

Computer Programming I 27

Example of structured flowchart

Page 28: Computer Programming - Lecture 2

28

Find the Maximum

Page 29: Computer Programming - Lecture 2

29

Find the Maximum - Structured

Page 30: Computer Programming - Lecture 2

30

Find the Maximum - Structured

Page 31: Computer Programming - Lecture 2

Computer Programming I 31

Unstructured Flowchart

break…

Page 32: Computer Programming - Lecture 2

Computer Programming I 32

Introduction to C++

Where did C++ come from? Derived from the C language C was derived from the B language B was derived from the BCPL(Basic Combined

Programming Language) language

Why the ‘++’?++ is an operator in C++

Page 33: Computer Programming - Lecture 2

Computer Programming I 33

C++ History

C developed by Dennis Ritchie at AT&T(American Telephone & Telegraph Company) Bell Labs in the 1970s. Used to maintain UNIX systems Many commercial applications written in C

C++ developed by Bjarne Stroustrup at AT&TBell Labs in the 1980s. Overcame several shortcomings of C Incorporated object oriented programming C remains a subset of C++

Page 34: Computer Programming - Lecture 2

Computer Programming I 34

A Sample C++ Program A simple C++ program begins this way

#include <iostream>using namespace std;

int main(){

And ends this way

return 0;}

Page 35: Computer Programming - Lecture 2

Computer Programming I 35

CommentsComments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.

C++ supports two ways to insert comments:

// line comment/* block comment */

/* my second program in C++ with more comments */ #include <iostream.h> int main () {

cout << "Hello World! "; // says Hello World! return 0;

}

Page 36: Computer Programming - Lecture 2

Computer Programming I 36

My first program in C++

// my first program in C++

#include <iostream.h>

int main ()

{

cout << "Hello World!";

return 0;

}

Hello World!

a comment line

a pound sign (#) is a directive for the preprocessor. It is not executable code but indications for the compiler.

tells the compiler's preprocessor to include the iostream standard header file.

Corresponds to the beginning of the main function declaration. The main function is the point where all C++ programs begin their execution.

cout is the standard output stream in C++to terminate a program

Page 37: Computer Programming - Lecture 2

Computer Programming I 37

Layout of a Simple C++ Program#include <iostream>

using namespace std;

int main()

{

variable_declarations

statement_1

statement_2

statement_last

return 0;

}

Page 38: Computer Programming - Lecture 2

Computer Programming I 38

Program Layout (1/2)

Programmers format programs so they are easy to read Place opening brace ‘{‘ and closing brace ‘}’

on a line by themselves Indent statements Use only one statement per line

Page 39: Computer Programming - Lecture 2

Computer Programming I 39

Program Layout (2/2)

Variables are declared before they are used Typically variables are declared at the beginning of

the program Statements (not always lines) end with a semi-colon

Include Directives #include <iostream> Tells compiler where to find information about items

used in the program iostream is a library containing definitions of cin and

cout

Page 40: Computer Programming - Lecture 2

Computer Programming I 40

Program Layout

using namespace std; Tells the compiler to use names in iostream in

a “standard” way

To begin the main function of the program

int main(){

To end the main function

return 0;}

Main function ends with a return statement

Page 41: Computer Programming - Lecture 2

Computer Programming I 41

Running a C++ Program

C++ source code is written with a text editor

The compiler on your system converts source code to object code.

The linker combines all the object codeinto an executable program.

Page 42: Computer Programming - Lecture 2

Computer Programming I 42

Compiler: is a program that translates a high-level language program, such as a C++ program, into a machine-language program that the computer can directly understand and execute.

Linking: The object code for your C++ program must be combined with the object code for routines (such as input and output routines) that your program uses. This process of combining object code is called linking and is done by a program called a linker. For simple programs, linking may be done for you automatically.

Concepts

Page 43: Computer Programming - Lecture 2

Computer Programming I 43

Run a Program

Obtain code Compile the code Fix any errors the compiler indicates and

re-compile the code Run the program Now you know how to run a program on

your system

Page 44: Computer Programming - Lecture 2

Computer Programming I 44

Testing and Debugging

Bug A mistake in a program

Debugging Eliminating mistakes in programs Term used when a moth caused a failed relay

on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.”

Page 45: Computer Programming - Lecture 2

Computer Programming I 45

Program Errors Syntax errors

Violation of the grammar rules of the language Discovered by the compiler

• Error messages may not always show correct location of errors

Run-time errors Error conditions detected by the computer at run-time

Logic errors (warning) Errors in the program’s algorithm Most difficult to diagnose Computer does not recognize an error

Page 46: Computer Programming - Lecture 2

Computer Programming I 46

End of Lecture 2