copyright © 2008 pearson addison-wesley. all rights reserved. chapter 1 introduction to computers...

49
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 1 Chapter 1 Introduction to Introduction to Computers and Computers and C++ Programming C++ Programming

Post on 19-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 1Chapter 1Introduction to Computers Introduction to Computers

and and

C++ ProgrammingC++ Programming

Our textbook

The SlidesThe Slides

These will be posted and left on the web These will be posted and left on the web for review purposes.for review purposes.

The slides are NOT a substitute for class The slides are NOT a substitute for class attendance and participation.attendance and participation.

Many of these slides are provided by the Many of these slides are provided by the author of the text. author of the text. I have frequently revised or added information I have frequently revised or added information

to existing slides as well as created new to existing slides as well as created new slides. slides.

Slide 1- 4

Overview - We'll cover this Overview - We'll cover this rather quicklyrather quickly

1.1 Computer Systems 1.1 Computer Systems -review this in the text -review this in the text

on your own as it was covered in 10051 and is on your own as it was covered in 10051 and is

not essential for this course.not essential for this course.

1.2 Programming and Problem Solving1.2 Programming and Problem Solving

1.3 Introduction to C++1.3 Introduction to C++

1.4 Testing and Debugging1.4 Testing and Debugging

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

1.21.2Programming and Problem-Programming and Problem-

SolvingSolving

Slide 1- 6

Algorithms Algorithms

AlgorithmAlgorithm A sequence of precise instructions thatA sequence of precise instructions that

leads to a solutionleads to a solution

ProgramProgram An algorithm expressed in a language the An algorithm expressed in a language the

computer can understandcomputer can understand

Slide 1- 7

Program DesignProgram Design

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

exist.exist.

Program Design ProcessProgram Design Process Problem Solving PhaseProblem Solving Phase

Result is an algorithm that solves the problemResult is an algorithm that solves the problem Implementation PhaseImplementation Phase

Result is the algorithm is translated into a Result is the algorithm is translated into a programming languageprogramming language

Slide 1- 8

Problem Solving PhaseProblem Solving Phase

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

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

program to run.program to run. Test the algorithm for correctnessTest the algorithm for correctness

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

Compile the source codeCompile the source code Locates errors in using the programming languageLocates errors in using the programming language

Run the program on sample dataRun the program on sample data Verify correctness of results Verify correctness of results

Results may require modification of Results may require modification of the algorithm and programthe algorithm and program

Slide 1- 9

Implementation PhaseImplementation Phase

Slide 1- 11

Object Oriented ProgrammingObject Oriented ProgrammingAbbreviated OOPAbbreviated OOP

Used for many modern programsUsed for many modern programs

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

its behaviorits behavior Program design phase involves designing Program design phase involves designing

objects and their algorithmsobjects and their algorithms

Slide 1- 12

OOP CharacteristicsOOP CharacteristicsEncapsulationEncapsulation Information hidingInformation hiding Objects contain their own data and algorithmsObjects contain their own data and algorithms

InheritanceInheritance Writing reusable codeWriting reusable code Objects can inherit characteristics from other objectsObjects can inherit characteristics from other objects

PolymorphismPolymorphism A single name can have multiple meanings depending A single name can have multiple meanings depending

on its contexton its context

Slide 1- 13

Software Life CycleSoftware Life Cycle

Analysis and specification of the task Analysis and specification of the task (problem definition)(problem definition)

Design of the software Design of the software (object and algorithm design)(object and algorithm design)

Implementation (coding)Implementation (coding)

Maintenance and evolution of the systemMaintenance and evolution of the system

ObsolescenceObsolescence

Slide 1- 14

Section 1.2 ConclusionSection 1.2 ConclusionCan you…Can you… Describe the first step to take when creating Describe the first step to take when creating

a program?a program?

List the two main phases of the program List the two main phases of the program design process?design process?

Explain the importance of the problem-solving phase?Explain the importance of the problem-solving phase?

List the steps in the software life cycle?List the steps in the software life cycle?

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

1.31.3Introduction to C++Introduction to C++

Slide 1- 16

Introduction to C++Introduction to C++Where did C++ come from?Where did C++ come from? Derived from the C languageDerived from the C language C was derived from the B languageC was derived from the B language B was derived from the BCPL languageB was derived from the BCPL language

Why the ‘++’?Why the ‘++’? ++ is an operator in C++ and results in a cute pun++ is an operator in C++ and results in a cute pun

Slide 1- 17

C++ HistoryC++ HistoryC developed by Dennis Ritchie at AT&TC developed by Dennis Ritchie at AT&TBell Labs in the 1970s.Bell Labs in the 1970s. Used to maintain UNIX systemsUsed to maintain UNIX systems Many commercial applications written in CMany commercial applications written in C

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

A simple C++ program begins this wayA simple C++ program begins this way

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main()int main(){{

And ends this wayAnd ends this way

return 0;return 0;}}

Slide 1- 18

A Sample C++ ProgramA Sample C++ Program

Note: In order to fit the code comfortably on a few number of slides, I won't always add comments.

This does NOT mean that you should do that also!!

<==== Optional

Slide 1- 22

Explanation of code (1/5)Explanation of code (1/5)Variable declaration line Variable declaration line

int number_of_pods, peas_per_pod, total_peas;int number_of_pods, peas_per_pod, total_peas;

Identifies names of three variables to name numbersIdentifies names of three variables to name numbers int means that the variables represent integersint means that the variables represent integers

Slide 1- 23

Explanation of code (2/5)Explanation of code (2/5)Program statementProgram statement

cout << “Press return after entering a number.\n”;cout << “Press return after entering a number.\n”;

cout (see-out) used for output to the monitorcout (see-out) used for output to the monitor

““<<“ inserts “Press…a number.\n” in the data<<“ inserts “Press…a number.\n” in the databound for the monitorbound for the monitor

Think of cout as a name for the monitorThink of cout as a name for the monitor““<<“ points to where the data is to end up<<“ points to where the data is to end up

‘‘\n’ causes a new line to be started on the monitor\n’ causes a new line to be started on the monitor

Slide 1- 24

Explanation of code (3/5)Explanation of code (3/5)Program statementProgram statement

cin >> number_of_pods;cin >> number_of_pods;

cin (see-in) used for input from the keyboardcin (see-in) used for input from the keyboard

““>>” extracts data from the keyboard >>” extracts data from the keyboard

Think of cin as a name for the keyboardThink of cin as a name for the keyboard““>>” points from the keyboard to a variable where the data >>” points from the keyboard to a variable where the data is storedis stored

Slide 1- 25

Explanation of code (4/5)Explanation of code (4/5)Program statementProgram statement

total_peas = number_of_pods * peas_per_pod; total_peas = number_of_pods * peas_per_pod;

Performs a computationPerforms a computation ‘‘*’ is used for multiplication*’ is used for multiplication ‘‘=‘ causes total_peas to get a new value based on=‘ causes total_peas to get a new value based on

the calculation shown on the right of the equal signthe calculation shown on the right of the equal sign

Slide 1- 26

Explanation of code (5/5)Explanation of code (5/5)

Program statementProgram statement

cout << number_of_pods; cout << number_of_pods;

Sends the value of variable number_of_pods Sends the value of variable number_of_pods to the monitorto the monitor

Slide 1- 27

Slide 1- 28

Program Layout (1/3)Program Layout (1/3)

Compiler accepts almost any pattern of lineCompiler accepts almost any pattern of linebreaks and indentationbreaks and indentation

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

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

Slide 1- 29

Program Layout (2/3)Program Layout (2/3)Variables are declared before they are usedVariables are declared before they are used Typically variables are declared at the beginning of Typically variables are declared at the beginning of

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

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

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

coutcout

Slide 1- 30

Program Layout (3/3)Program Layout (3/3)using namespace std;using namespace std; Tells the compiler to use names in iostream inTells the compiler to use names in iostream in

a “standard” waya “standard” way

To begin the main function of the programTo begin the main function of the programint main()int main()

{ { To end the main functionTo end the main function return 0; return 0; } } Main function ends with a return statementMain function ends with a return statement

Slide 1- 31

Running a C++ ProgramRunning a C++ Program

C++ source code is written with a text C++ source code is written with a text editoreditor

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

The linker combines all the object codeThe linker combines all the object codeinto an executable program.into an executable program.

Use ssh to connect to the computer on which you Use ssh to connect to the computer on which you have an account.have an account.

I will use putty for ssh and loki.cs.kent.edu.I will use putty for ssh and loki.cs.kent.edu.

In the lab you will use a similar version of ssh. In the lab you will use a similar version of ssh. However, I want to have be able to set the font larger However, I want to have be able to set the font larger than that one allows.than that one allows.

If you want putty for your machine, go toIf you want putty for your machine, go to

http://www.chiark.greenend.org.uk/~sgtatham/putty/

Choose downloads and download Choose downloads and download

PuTTY (the Telnet and SSH client itself)PuTTY (the Telnet and SSH client itself)

Slide 1- 32

Running a C++ ProgramRunning a C++ Program

Make ssh SelectionsMake ssh Selections

Optional Optional Selection to Selection to Increase Font Increase Font SizeSize

Press OK and then Open to obtain a Press OK and then Open to obtain a window in loki.cs.kent.eduwindow in loki.cs.kent.edu

Login with your departmental username Login with your departmental username and password.and password.

Create a Subdirectory and Create a Subdirectory and Move ThereMove There

create cs1

move to cs1

check path to cs1

list contents of cs1

currently empty

Code We Will RunCode We Will RunUse vim as the EditorUse vim as the Editor

Invoke vimInvoke vim

Type i to start the insertion of codeType i to start the insertion of code

To Save and Exit push ESC To Save and Exit push ESC Then shift :Then shift :

Then wq for write and quitThen wq for write and quit

testing.cpp is written and is listed in the testing.cpp is written and is listed in the current directorycurrent directory

Compile and RunCompile and Run

compile

executable file for testing

run testing.cpp

Output is correct

list contents of diretory

To Use a Name Other Than To Use a Name Other Than a.out for the Executablea.out for the Executable

Slide 1- 44

Section 1.3 ConclusionSection 1.3 ConclusionCan you…Can you…

Describe the output of this line?Describe the output of this line?

cout << “C++ is easy to understand.”;cout << “C++ is easy to understand.”;

Explain what this line does?Explain what this line does?

cin >> peas_per_pod;cin >> peas_per_pod;

Explain this? #include <iostream>Explain this? #include <iostream>

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

1.41.4Testing and DebuggingTesting and Debugging

Slide 1- 46

Testing and DebuggingTesting and DebuggingBugBug A mistake in a programA mistake in a program

DebuggingDebugging Eliminating mistakes in programsEliminating mistakes in programs Term used when a moth caused a failed relayTerm used when a moth caused a failed relay

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

Slide 1- 47

Program ErrorsProgram ErrorsSyntax errorsSyntax errors Violation of the grammar rules of the languageViolation of the grammar rules of the language Discovered by the compilerDiscovered by the compiler

Error messages may not always show Error messages may not always show correct location of errorscorrect location of errors

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

run-timerun-timeLogic errorsLogic errors Errors in the program’s algorithmErrors in the program’s algorithm Most difficult to diagnoseMost difficult to diagnose Computer does not recognize an errorComputer does not recognize an error

Slide 1- 48

Section 1-4 ConclusionSection 1-4 ConclusionCan you…Can you… Describe the three kinds of program errors?Describe the three kinds of program errors?

Tell what kind of errors the compiler catches?Tell what kind of errors the compiler catches?

What kind of error is produced if you forget a What kind of error is produced if you forget a punctuation symbol such as a semi-colon?punctuation symbol such as a semi-colon?

Tell what type of error is produced when a Tell what type of error is produced when a program runs but produces incorrect results?program runs but produces incorrect results?

In the Lab You Will Learn About the FollowingIn the Lab You Will Learn About the Following

sshssh

The file structure for UNIX/LinuxThe file structure for UNIX/Linux

Simple UNIX/Linux commands -Simple UNIX/Linux commands -

lsls catcat mkdirmkdir deldel rmdirrmdir pwdpwd

cdcd cpcp mvmv manman moremore g++g++

gdbgdb exitexit aproposapropos

Using the editor vimUsing the editor vim

Using g++ and the debugger gdbUsing g++ and the debugger gdb

How to submit programsHow to submit programs