cs-150 problem solving & programming i with c++ week 1: overview tue/thur january 13,15 2015...

Post on 15-Dec-2015

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CS-150Problem Solving & Programming I with C++

Week 1: OverviewTue/Thur January 13,15 2015

Textbook materials: C++ Programming: From Problem Analysis to Program Design, 7th Edition ( 6th Ed.? )

New materials are being updated to our cs150 site,…

http://www.cs.odu.edu/~cboyle/

http://www.cs.odu.edu/~cs150/

2

CS-150• Catalog Course Description: Lecture 3 hours; Laboratory 2.5 hours; 4

creditsIntroduction to computer-based problem solving and programming in C++.

• Topics include problem solving methodologies, program design, algorithm development, and testing.

• C++ language concepts include variables, data types and expressions, assignment, control-flow statements, arrays, sorting, functions, pointers, and linked lists.

• Lecture – twice a week.• Lab - once a week…required weekly, assignments.

• Recitation –

3

Textbook

Malik, C++ Programming: from Problem Analysis to Programming Design ,

7th edition

Cengage Course Technology,

1133626386 978-1133626381

Info on CS web site and ODU bookstore site.

4

Spring 2015 Session Dates:

http://www.odu.edu/academics/calendar/spring

5

Lab this week!1)      REGISTER for YOUR CS accounts. You will need

to log in using the guest account for the first lab. The Lab instructor will provide this information.

2)  Demo: how to download a CPP file for lab, create a CS150 folder in the Z drive, and create an organized structure so it’s easy to keep track of your work throughout the semester, e.g.:

3)  Practice opening, reviewing, compiling, & running a CPP file

6

z:\z:\CS150\lab-assignment-1\lab-assignment-1.cpp

********************************************************************************

                      CS150: Spring 2015 - Lab Assignment Example

********************************************************************************

 Enter your first name: Stewie  

Enter your last name: Griffin

Please confirm: Is your name Stewie Griffin? (Y/N): Y

********************************************************************************

 

Enter today's date any way you like: Tuesday, 26 August 2014

Enter the year you were born: 2012

********************************************************************************

 

Your CS username is most likely: sgriffin

You are probably turning 2 this year.

 

Writing output to sgriffin-lab-assignment-1.txt.

You can find it in the same folder as the CPP.7

Teaching Assitants

8

A Brief Overview of the History of Computers

• Early calculation devices− Abacus, Pascaline− Leibniz device− Babbage machines: difference and analytic engines− Hollerith machine

C++ Programming: From Problem Analysis to Program Design, Fourth, Fifth & Sixth Edition 10

Terminology

• Algorithm: A set of steps that defines how a task is performed

• Program: A representation of an algorithm• Programming: The process of developing a

program• Software: Programs and algorithms• Hardware: Equipment

History of Algorithms

• The study of algorithms was originally a subject in mathematics.

• Early examples of algorithms− Long division algorithm

− Euclidean Algorithm

• Gödel's Incompleteness Theorem: Some problems cannot be solved by algorithms.

The Euclidean algorithm

Origins of Computing Machines

Greece, Ancient Assyria, Egypt,…..

• The ABACUS most likely existed in Babylonia around 3000 B.C.

− Abacus: positions of beads represent numbers

An Abacus

• Early calculation devices− Abacus, Pascaline

− Leibniz device

− Jacquard’s weaving looms

− Babbage machines: difference and analytic engines

− Hollerith machine

• Early computer-like machines− Mark I

− ENIAC

− Von Neumann architecture

− UNIVAC

− Transistors and microprocessors16

Origins of Computing Machines

• Gear-based machines (1600s-1800s)• Positions of gears represent numbers• Blaise Pascal, Wilhelm Leibniz, Charles Babbage

• 1622: invention of slide rule

• 1642: invention of mechanical calculator by Blaise Pascal

• 1694: Leibniz Wheel expands arithmetic operations

Charles Babbage• Invents Difference Engine in 1823

− Device adds, subtracts, multiplies, divides

• Designs Analytical Engine − Incorporated components akin to modern computer

systems: I/O devices, memory, CPU

− Storage of programs in Babbage’s Analytical Engine - Gear positions

Ada Lovelace Byron− First programmer!− Program loop concept − Ada programming language namesake

Early Data Storage

Joseph Jacquard− First used in Jacquard Loom (1801) to store

patterns for weaving cloth

− Allows the operator to input and store parameters through use of punch cards that are oriented with selection pins.

− Popular through the 1970’s

Stored Program Concept!

Early Data Storage

Herman Hollerith

• Invented an electromechanical counter in 1880s.

− Designed as a single-purpose machine, it was used in tabulating the 1890 US census.

− Used punch cards as input

Early Data Storage

Herman Hollerith

• The company created around this technology becomes International Business Machine: IBM

− 1944 – IBM Mark I computer

The Mark I computer

Early Computers

• Based on mechanical relays− 1940: Stibitz at Bell Laboratories− 1944: Mark I: Howard Aiken and IBM at Harvard

• Based on vacuum tubes− 1937-1941: Atanasoff-Berry at Iowa State− 1940s: Colossus: secret German code-breaker− 1940s: ENIAC: Mauchly & Eckert at U. of Penn.

Progress in Early Computers

Charles Sanders Peirce− His work with electric switches extends the

work of Boole by emulating the true/false conditions of Boolean algebra

− Benjamin Burack implements concepts in 1936 logic machine

− John Atanasoff and Clifford Berry build a computer using vacuum tubes

Categories of Computers

• Mainframe computers• Midsize computers• Micro computers (personal computers)• Handheld devices• Appliances• ?????• ???• drones?

C++ Programming: From Problem Analysis to Program Design, 4th & 6th Edition 28

Elements of a Computer System

• Hardware

• Software: programs that do specific tasks− System programs control the computer

• ex: Operating system

− Application programs• Word processors• Spreadsheets• Games

29

CPUMain memory: RAMInput/output devicesSecondary storage

CPU (Central Processing Unit)

• CU (Control Unit):− Fetches and decodes instructions− Controls flow of information in and out of MM− Controls operation of internal CPU components

• PC (program counter): points to next instruction to be executed

• IR (instruction register): holds instruction currently being executed

• ALU (arithmetic logic unit): carries out all arithmetic and logical operations

30

•Input devices feed data & programs into computers

–Keyboard –Mouse –Secondary storage

•Output devices display results

–Monitor–Printer–Secondary storage

Main Memory

• Directly connected to the CPU • All programs loaded here before execution• All data must be brought here before use• Power off == data in main memory is lost

32

Secondary Storage

• Secondary storage: device that stores information permanently

• Examples of secondary storage:− Hard disks

− Flash drives

− Floppy disks

− Zip disks

− CD-ROMs

− Tapes

33

?

The Language of a Computer

• Digital signals are sequences of 0s and 1s• Binary code: - A sequence of 0s and 1s

001101011101011001101110100110

• Machine language: language of a computer

• Bit: (binary digit) : The digit 0 or 1

• Byte: A sequence of eight bits

34

35

Coding Schemes

• ASCII (American Standard Code for Information Interchange) − 128 characters

− A is encoded as 1000001 (66th character)

− 3 is encoded as 0110011

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 37

Coding Schemes (continued)

• EBCDIC− Used by IBM

− 256 characters

• Unicode − 65536 characters

− Two bytes are needed to store a character

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 38

39

Evolution of Programming Languages

• Early computers were programmed in machine language

• To calculate wages = rates * hours in machine language:

100100 010001 //Load

100110 010010 //Multiply

100010 010011 //Store

40

Assembly Language

• Assembly language instructions are mnemonic • Assembler: translates a program written in

assembly language into machine language

High-Level Languages

• High-level languages include Basic, FORTRAN, COBOL, Pascal, C, C++, C#, and Java, ect..

• Compiler: translates a program written in a high-level language into machine language

• The equation wages = rate • hours can be written in C++ as:

wages = rate * hours;

41

What?

42

Meanwhile,… back in class,….

43

Outline•Computer Programming Process

•Algorithms and programming languages

44

Computer ProgrammingComputer program

A sequence of instructions to be performed by a computer

Computer programming

The process of planning a sequence of steps for a computer to follow

Programming Process

•Problem-solving phase

•Implementation phase

•Maintenance phase

45

Programming Process1/3

Problem-solving phase

•Analysis and specification ( understand and define problem, and what is expected of solution)

•General solution (algorithm: a logical sequence of steps that solves the problem)

•Verification (Follow steps to make sure solution solves the problem)

Implementation phase

•Concrete solution (Program in a Programming language)

•Testing (make sure the program produces the desired results)

Maintenance phase

•Use Program

•Maintain Program (meet changing requirements)

46

Programming Process2/3

Analysis and Specification

General solution (algorithm)

Verification

Concrete solution

(Program)

Testing

Maintenance Phase

In “Programming and Problem Solving with C++”, 3rd Edition, Jones and Bartlett Publishers, 2002

Documentation: writing program documentation, and user

manuals

47

Programming Process3/3

How about we take a shortcut and start the programming process by the implementation phase?

Costly shortcut

Develop a general solution (algorithm) first

Think first and code later!

48

Algorithm1/3

Algorithm

•An ordered set of unambiguous executable steps, defining a terminating process

•A step-by-step procedure for solving a problem in a finite amount of time

1. Make a list of all positive integers

2. Arrange the list in descending order (from largest to smallest)

3. Extract the first integer from the list

What are the problems with these instructions?

49

Algorithm2/3

•Difference between an algorithm and its representation

Analogous to difference between a story and a book

•An algorithm is abstract and can be represented in many ways

Algorithm for converting from Celsius to Fahrenheit can be represented as

1. F = (9/5) C + 32 (algebraic equation)

2. “ Multiply the temperature reading in Celsius by 9/5 and then add 32 to the product”

An algorithm can be represented using some sort of language

1950s, 1960s represented using flowcharts

pseudocode (precisely defined textual structures)

50

Algorithm3/3

An algorithm for starting the car

1. Insert the key in ignition

2. Make sure transmission is in Park (or Neutral)

3. Depress the gas pedal

4. Turn key to start position

5. If engine starts within six seconds, release key to ignition position

6. If engine does not start in six seconds, release key and gas pedal, wait ten seconds, and repeat steps 3 through 6, but not more than five times

7. If the car does not start, call the garage

51

Programming Language1/3

A set of rules, symbols, and special words used to construct a computer program. There are rules for syntax (grammar) and semantics (meaning)

Machine language

•Binary-coded instructions

•Closely coupled with design of computer hardware

Assembly language

•Low-level programming language in which a mnemonic is used to represent each of the machine language instructions

•We have seen an example in chapter 2 from Brookshear Text

•We need an assembler

Translate an assembly language program into machine code

52

Programming Language2/3

High-level language

•closer to English and other natural languages

•C++, Java, C, Fortran, Ada, Pascal, COBOL, BASIC

•We need a compiler

Translate a high-level language program into machine code

•Source program

Program written in a high-level language

•Object program

Machine language version of a source program

•Difference between compilation and execution of a program

53

Programming Language3/3

•Some programming languages are translated by an interpreter (some versions of BASIC)

•Interpreter translates and executes each instruction in the source program

•Java uses both a compiler and interpreter

54

A C++ Program

#include <iostream>using namespace std;int main() { cout << "My first C++ program." << endl; cout << "The sum of 2 and 3 = " << 5 << endl; cout << "7 + 8 = " << 7 + 8 << endl; return 0;}

Sample Run: My first C++ program.The sum of 2 and 3 = 57 + 8 = 15

55

Processing a Program

• To execute a C++ program:− Use an editor to create a source program in C++

− Preprocessor directives begin with # and are processed by the preprocessor

− Use the compiler to:• Check that the program obeys the rules• Translate into machine language (object program)

− Software Development Kit (SDK) may be used to create a program

56

Processing a Program (contd) To execute a C++ program (continued):

−Linker: • Combines object program with other programs provided

by the SDK to create executable code

−Loader: • Loads executable program into main memory

−The last step is to execute the program

58

Programming is a process of

problem solving

59

Programming with the Problem Analysis–Coding–Execution Cycle

• Programming is a process of problem solving

One problem-solving technique:

− Analyze the problem

− Outline the problem requirements

− Design steps (algorithm) to solve the problem

• Algorithm:

− Step-by-step problem-solving process

− Solution achieved in finite amount of time

60

Programming with the Problem Analysis–Coding–Execution Cycle

• Step 1 - Analyze the problem− Outline the problem and its requirements

− Design steps (algorithm) to solve the problem

• Step 2 - Implement the algorithm− Implement the algorithm in code

− Verify that the algorithm works

• Step 3 - Maintenance− Use & modify the program if problem domain changes

Analyze the Problem

• Thoroughly understand the problem• Understand problem requirements

− Does program require user interaction?

− Does program manipulate data?

− What is the output?

• If the problem is complex, divide it into subproblems− Analyze each sub-problem as above

62

Design an Algorithm

• If problem was broken into subproblems− Design algorithms for each subproblem

• Check the correctness of algorithm− Can test using sample data

− Some mathematical analysis might be required

63

64

Problem Solving Techniques

•You follow algorithms every day in your life

•We need to learn how to design algorithms not simply follow them

•Some Strategies to solve problems

Ask questions

Look for things that are familiar

Means-Ends Analysis

Divide and Conquer

65

Strategies: Ask QuestionsWhen you are given a problem, you ask questions (What, Why, When, and Where?)

In the context of programming

•What do I have to work with (What is my data)?

•What do the data items look like?

•How much data is there?

•How will I know when I have processed all the data?

•What should my output look like?

•How many times is the process going to be repeated?

•What special error conditions might come up?

66

Strategies: Look for Familiar Things

•Never reinvent the wheel

If a solution exists USE IT

Finding the daily high and low temperatures

is really the same problem as

Finding the highest and lowest grades on a test

Both problems can be abstracted as being

Find largest and smallest values in a set of numbers

67

Strategies: Means-Ends Analysis

Beginning state and End state are often given

•You need to define a set of actions that can be used to get from one to the other

•Once you have a set of actions, you need to work out the details

Translated to computer programming

Begin by writing down what the input is? (Beginning state)

What the output should be? (End state)

What actions can be performed to obtain results from input data?

68

Strategies: Divide and ConquerBreak up large problems into smaller problems that are easier to handle

(Top-Down approach)

Hard problem

Easy subproblem

Easy subproblem

Hard subproblem

Easy subproblem

Easy subproblem

69

An Example1/3

Compute the area of a circle

Problem statement - We need an interactive program (user will input data) that computes the area of a circle. Given the circle radius, the circle area should be displayed on the screen

Input/Output description

Input Circle radius

Output Circle area

Algorithm development (set of steps, decomposition outline)

1. Read value of circle radius (r)

2. Compute circle area as pi * r2

3. Print the value of circle area How do we represent more complex algorithms?

Pseudocode, flowcharts (will introduce flowcharts later)

70

An Example2/3

A divide and conquer block diagram of our problem

Circle area

Read radius Print circle areaCompute area

Pseudocode

Prompt the user for the circle radius (put a message on the screen)

Read radius

Assign Circle area the value pi * radius2

Write Circle area on the screen

Stop

71

An Example3/3

Convert algorithm into a C++ program

#include <iostream.h>

void main ()

{

float pi = 3.14159f;

float radius, area;

cout << "Enter the radius of the circle: ";

cin >> radius;

area = pi* radius * radius;

cout << "The area of the circle is: " << area << endl;

}

Write the Code

• Once the algorithm is designed and correctness verified− Write the equivalent code in high-level

language

• Enter the program using text editor

72

Compiling and Linking

• Run code through compiler • If compiler generates errors

− Look at code and remove errors

− Run code again through compiler

• If there are no syntax errors− Compiler generates equivalent machine code

• Linker links machine code with system resources

73

The Loader and Executing

• Once compiled and linked, loader can place program into main memory for execution

• The final step is to execute the program• Compiler guarantees that the program follows

the rules of the language− Does not guarantee that the program will run

correctly

74

75

Example 1-1

•Create a program to determine the perimeter and area of a rectangle

76

Example 1 Analyze the Problem

• Design an algorithm to find the perimeter and area of a rectangle

• The perimeter and area of the rectangle are given by the following formulas:

perimeter = 2 * (length + width)

area = length * width

77

Example 1 Design the Algorithm

• Algorithm:

− Get length of the rectangle

− Get width of the rectangle

− Find the perimeter using the following equation:

perimeter = 2 * (length + width)

− Find the area using the following equation:

area = length * width

- Display the results:

78

Example 1 Write the Code

cin length // Input length

cin width // Input width

perimeter=2*(length + width) // Calc #1

area = length * width // Calc #2

cout perimeter // Output width

cout area // Output width

PsuedoCode

79

Compiling and Linking

• Codeblocks

80

Programming Methodologies

• Two popular approaches to programming design

− Structured

− Object-oriented

81

Structured Programming

• Structured design:

− Dividing a problem into smaller subproblems

• Structured programming:

− Implementing a structured design

• The structured design approach is also called:

− Top-down (or bottom-up) design

− Stepwise refinement

− Modular programming

Object-Oriented Programming

• Identify components called objects• Specify relevant data and possible operations

to be performed on that data• Each object consists of data and operations

on that data• An object combines data and operations on

the data into a single unit

82

Object-Oriented Programming (continued)

• A programming language that implements OOD is called an object-oriented programming (OOP) language

• Learn how to represent data in computer memory, how to manipulate data, and how to implement operations

• Write algorithms and implement them in a programming language

83

Object-Oriented Programming (continued)

• Learn how to combine data and operations on the data into a single unit called an object

• C++ was designed to implement OOD• OOD is used with structured design

84

ANSI/ISO Standard C++

• C++ evolved from C • C++ designed by Bjarne Stroustrup at Bell

Laboratories in early 1980s• C++ programs were not always portable from

one compiler to another• In mid-1998, ANSI/ISO C++ language

standards were approved

85

Summary

• Computer: electronic device that can perform arithmetic and logical operations

• Computer system has hardware and software• Central processing unit (CPU): brain• Primary storage (MM) is volatile; secondary

storage (e.g., disk) is permanent• Operating system monitors the overall activity

of the computer and provides services

86

87

Summary (continued)

• Various kinds of languages, such as machine language, assembly, high-level

• Algorithm: step-by-step problem-solving process; solution in finite amount of time

• Problem-solving process has three steps:− Analyze problem and design an algorithm

− Implement the algorithm in code

− Maintain the program

Summary (continued)

• Structured design: − Problem is divided into smaller subproblems

− Each subproblem is solved

− Combine solutions to all subproblems

• Object-oriented design (OOD): a program is a collection of interacting objects− Object: data and operations on those data

88

top related