02 Intro to Cpp

download 02 Intro to Cpp

of 101

Transcript of 02 Intro to Cpp

  • 8/2/2019 02 Intro to Cpp

    1/101

  • 8/2/2019 02 Intro to Cpp

    2/101

    Machine Language

    Ada

    PascalFortranCOBOL

    Assembly Language

    Smalltalk

    Visual BasicBASIC

    JavaC and C++

    Programming Languages

    Programming languages are artificial languagescreated to tell the computer what to do

    They consist of vocabulary and a set of rules

    (grammar/syntax) to write programs

    The software development life cycle (SDLC) is anorganized method of software development

  • 8/2/2019 02 Intro to Cpp

    3/101

    C++ Predecessors

    Early procedural languages included

    FORTRAN: Formula Translation

    ALGOL: Algorithmic Language

    COBOL: Common Business Oriented LanguageBASIC: Beginners All-purpose Symbolic

    Instruction Code

    Pascal

    CSmalltalk, Simula, etc. were the object-oriented

    predecessors of C++

    Thi d i d F h

  • 8/2/2019 02 Intro to Cpp

    4/101

    The Evolution

    of Programming

    Languages

    Third- eneration and Fourth-Generation (High-Level) Languages

  • 8/2/2019 02 Intro to Cpp

    5/101

    First-Generation Languages

    Machine language:

    Consists of binary numbers(0s and 1s)

    Is the earliest programming

    language Is the only language the

    computer understandswithout translation

    It is machine dependent;each family of processorshas its own machinelanguage

  • 8/2/2019 02 Intro to Cpp

    6/101

    Second-Generation Languages

    Assembly language:

    Resembles machinelanguage

    Is a low-level language

    Uses brief abbreviations forprogram instructions.

    Abbreviations are calledmnemonics

    A program is written insource code (text file) andtranslated into machine

    language by an assembler

  • 8/2/2019 02 Intro to Cpp

    7/101

    Third-Generation Languages

    Procedural languages:

    Are high-level languages that tell the computerwhat to do and how to do it

    Create programs at a high level of abstractionAre easier to read, write, and maintain than

    machine and assembly languages

    Use a compiler or interpreter to translate code

    Fortran and COBOL are third-generationlanguages

  • 8/2/2019 02 Intro to Cpp

    8/101

    Compilers and Interpreters

    An interpreter translates source code one line at a timeandexecutes the instruction

    A compiler is a program that changes source code to objectcode, all in one shot

    Example of an interpreted language: BASIC; a compiled

    language: C

    Th t t i i th

  • 8/2/2019 02 Intro to Cpp

    9/101

    The reat o tware risis o the60s

    Spaghetti Code and the Great Software Crisis:goto statements resulted in programs that were

    difficult to follow

    This made them difficult to modify, maintain, andeven develop!

    This problem led to the software crisis of the1960s

    Programs were not ready on timePrograms exceeded their budgets

    Programs contained too many errors

    Customers were not satisfied

    Management was also very frustrated!

    t t d P i t th

  • 8/2/2019 02 Intro to Cpp

    10/101

    tructured Programming to therescue

    Structured programming languages:

    Were developed to improve software

    developmentInclude Algol and Pascal

    Are well-structured and organized

    Forbid the use of goto statementsUse three fundamental control structures

    Sequence, Selection, Repetition

    M d l P i L

  • 8/2/2019 02 Intro to Cpp

    11/101

    Modular Programming Languagesdeveloped in the 70s

    Modular programming languages:

    Were developed because of problems in

    structured programming languagesAre used to create programs that are divided

    into separate modules

    Each module carries out a special function

    Require specified input to produce specifiedoutput

  • 8/2/2019 02 Intro to Cpp

    12/101

    Fourth-Generation Languages Fourth-generation languages are non-procedural, high-level

    specification languages

    They do not force programmers to follow procedures to produce results(theyre very close to English, sometimes)

    Types of fourth-generation languages include:

    Report generators

    Languages for printing database reports (generate a programto generate

    the report) Query languages

    Languages for getting information out of databases (generate a programtoprocess a query or generate a form)

    Also include visually-oriented languages

    More ambitious 4GL environments attempt to automatically generatewhole systems from the outputs of CASE tools, specifications of screensand reports, and possibly also the specification of some additionalprocessing logic, including data flow diagrams, entity relationshipdiagrams, entity life history diagrams

    Fifth-generation languages

    These include artificial intelligenceand neural networksorientedlanguages

  • 8/2/2019 02 Intro to Cpp

    13/101

    SKIP: Object-Oriented Programming

    Object-oriented programming (OOP):

    Relies on component reusability

    The ability to produce program modules thatperform a specific task

    Eliminates the distinction between programsand data

    Uses objects that contain data andprocedures

  • 8/2/2019 02 Intro to Cpp

    14/101

    SKIP: Objects Objects are units of information that contain data as

    well as methods that process and manipulate the data

    Classes of objects:

    Hierarchy or category of objects

    Objects at the top of the category are broader in

    scope than the subclass objectsObjects near the bottom are narrower in scope

    Inheritancerefers to an objects capacity to pass onits characteristics to its subclasses

  • 8/2/2019 02 Intro to Cpp

    15/101

  • 8/2/2019 02 Intro to Cpp

    16/101

    3GL Programming Languages

    Most high-level programming languages canbe categorized into one of three maincategories:

    Procedural Languages (FORTRAN, BASIC,COBOL, Pascal, etc.)

    Object-Oriented Languages (Smalltalk, Effiel,etc.)

    Hybrid Languages allow both OO andProcedural (such as C++)

  • 8/2/2019 02 Intro to Cpp

    17/101

    3GL: Procedure-oriented (structured) languages Programmers concentrate on the procedures used in the

    program

    Procedure: a logically consistent set of instructions which is usedto produce one specific result

    3GL: Object-oriented languages

    Items are represented using self-contained objects

    Can be used to create programs for graphical windowsenvironments

    4GLs: fourth-generation languages Permit users to access and format information without the

    need for writing any procedural code

    Use high-level English-like instructions to specify what to do, not

    how to do it .

    3GL vs. 4GL

  • 8/2/2019 02 Intro to Cpp

    18/101

    Procedural Programming Basics

    The purpose of most applicationprograms is to process data toproduce specific results

    Basic procedural operations.

  • 8/2/2019 02 Intro to Cpp

    19/101

    What Can a Procedural Program Do?

    A linear, procedural program is structured toinstruct a computer to:

    Read InputCalculate

    Store data

    Write Output

    Work in a sequential progression (Sequence)Compare and branch (Selection)

    Iterate or Loop (Repetition)

    Ad t f P d l

  • 8/2/2019 02 Intro to Cpp

    20/101

    Advantages of ProceduralProgramming

    Easier to test and debug Structured walkthroughs of the code

    goto-less

    I.e., theyre well-structured and include the three

    fundamental control structures Standard method for solving a problem

    A single program can be written by more than oneprogrammer

    By dividing the program up into modules

    Programs can share routines (again, because ofmodularization)

  • 8/2/2019 02 Intro to Cpp

    21/101

    Whats structured programming?

    A Structure is One or More Instructions

    (Flowchart Symbols) Combined According toRules

    E.g., only one point of entry and exit

    Structured programming is a set of rules that

    prescribe good style habits for programmer.

    An organized, well structured code

    Easily sharable; easy to debug and test

    Requires shorter time to develop, test, and update

    The key idea is that any numerical algorithm can

    be composed using the three fundamental control

    structures:

    Sequence, selection, and repetition

    a re e es or r ng a

  • 8/2/2019 02 Intro to Cpp

    22/101

    a re e u es or r ng aStructured Program?

    3 basic control structures:

    Sequence

    Selection (decision)

    Repetition (looping or iteration)

  • 8/2/2019 02 Intro to Cpp

    23/101

    Modularization

    Modular Program: a program consisting ofinterrelated segments arranged in a logical andunderstandable form

    Easier to develop, correct, and modify than otherkinds of programs

    Module: a small segment which is designed toperform a specific task

    A group of modules is used to construct amodular program

    Modular Programming

  • 8/2/2019 02 Intro to Cpp

    24/101

    Modular Programming Behind most software development over the last century Encourages subroutines Large programs are divided by functional parts into

    subroutines or modules Go to instructions only permitted within subroutines Three objectives when creating routines:

    Smaller, simpler routines Breakup complex routines into simple functions

    Strong cohesion Routine does one function such as printing

    Instructions are closely related

    Loose coupling Non-existent or weak connection between routines

    One routine does not depend on other routines

  • 8/2/2019 02 Intro to Cpp

    25/101

    SUBPROGRAM (function)SUBPROGRAM1 . . .

    SUBPROGRAM1

    a meaningful collection

    of SEQUENCE,SELECTION, REPETITION

    (LOOP), or SUBPROGRAMS

  • 8/2/2019 02 Intro to Cpp

    26/101

    Introduction to C++

    Modules in C++ can be classes or functions

    Function: accepts an input and produces an

    output by processing the input in some fashion A functions processing is encapsulatedand

    hiddenwithin the function

  • 8/2/2019 02 Intro to Cpp

    27/101

    A Multiplying Function

  • 8/2/2019 02 Intro to Cpp

    28/101

    Classes and Functions

    Function: encapsulates a set of operations, whilea classencapsulates data plus one or more sets

    of operations Class: contains both data and functions used to

    manipulate the data

    Identifier: a name given to an element of the

    language, such as a class or function

    The o tware Development Li e

  • 8/2/2019 02 Intro to Cpp

    29/101

    The o tware Development Li eCycle (SDLC)

    The SDLC was introduced in the 1970s to addressproblems in creating programs

    It provides an organized plan for breaking down thetask of program development into manageable parts

    Five phases of the SDLC:

    1. Defining the problem

    2. Designing the program

    3. Coding the program

    4. Testing, debugging, and formalizing the program

    5. Implementing and maintaining the program

  • 8/2/2019 02 Intro to Cpp

    30/101

    Phase 1: Defining the Problem

    The first step in program development

    What do you want to solve? What is the objective and question? Get the requirements from the client (possibly other software

    engineers)

    Systems analysts provide program specifications (specs) to the

    programmers The specs define:

    Input data

    Processing Output

    Including the appearance of the user interface Software engineers need clear specifications (as opposed to

    requirements):

    Clear, specific statement of goal Expected output Expected input

  • 8/2/2019 02 Intro to Cpp

    31/101

    Phase 2: Designing the Program

    Programmers create the programs design

    Top-down designfocuses on the programs main goal(main routine), then breaks the program into manageablecomponents (subroutines/modules)

    Control structures are used to see how each subroutine

    will do its job Makes programming easier to develop, debug, and

    maintain

    Developing an algorithm, which is a step-by-step descriptionof how to arrive at a solution

    Program design tools:

    Structure charts show the top-down design

    Flow charts show the logic of program

    Pseudocode alternative to flow charts

  • 8/2/2019 02 Intro to Cpp

    32/101

    Structured Design

    Structured programming implements structured design

    Control structures are logical constructs that specifyhow the instructions in a program are to be executed

    Three fundamental types of control structures:

    Sequence control structure Instructions areexecuted in the order in which they appear

    Selection control structures The programbranches to different instructions depending on

    whether a condition is met; IFTHENELSE Repetition control structure The program

    repeats the same instructions over and over; DO-WHILE and DO-UNTIL

    S Ch d Fl h

  • 8/2/2019 02 Intro to Cpp

    33/101

    Structure Chart

    Flowchart

    Structure Chart and Flowchart

    Ph 3 C di th P

  • 8/2/2019 02 Intro to Cpp

    34/101

    Phase 3: Coding the Program

    Codingrequires the translation of the algorithm intospecific program instructions

    An appropriate programming language is chosen,

    and the code is typed according to its syntax rules Documentationis created for future use

    Best if the documentation is done in-line using a tool likeJavaDoc, Doxygen, etc.

    The variable names and definitions, a description ofthe files needed, and the layout of the output areproduced

    A user manualis developed to explain how the

    program works

    Phase 4: Testing and Debugging the

  • 8/2/2019 02 Intro to Cpp

    35/101

    Phase 4: Testing and Debugging theProgram

    Testing and debugging eliminate all errors

    Syntax and logic errors are corrected Debugging is the process of eliminating errors

    Phase 5: Implementing and

  • 8/2/2019 02 Intro to Cpp

    36/101

    Phase 5: Implementing andMaintaining the Program

    The program is:

    Tested by usersThoroughly documented

    Maintained and evaluated regularly

    Al ith

  • 8/2/2019 02 Intro to Cpp

    37/101

    Algorithms

    Algorithm: A step-by-step sequence of instructionsthat must terminate

    Pseudocode

    Use of English-like phrases to describe an algorithm

    Formula

    Use of mathematical equations to describe analgorithm

    FlowchartUse of diagrams that employ symbols to describe an

    algorithm

    P D i P

  • 8/2/2019 02 Intro to Cpp

    38/101

    Program Design Process

    AL-KHOWARIZMI

    Grace M. HopperFirst Bug

    Algorithm Design

    (underlying logic of program)

    Program Composition

    Debug & test

    (error free & reliable)

    Documentation

    Maintenance

    75% of costs!

    Whats an Algorithm?

  • 8/2/2019 02 Intro to Cpp

    39/101

    Whats an Algorithm?

    A predetermined series of

    instructionsfor carrying out atask in a finite number of steps

    I.e., Baking A Cake!

    Two commonly used tools tohelp document the program

    logic (the algorithm):Flowcharts and Pseudocode.

    Generally, Flowcharts workwell for small problems butPseudocode is used for larger

    problems

  • 8/2/2019 02 Intro to Cpp

    40/101

    How to make a plan ?

    Do a hand calculation (brainstorming!)

    Make a flowchart

    Visio or dia

    Write the Pseudocode

    Flowchart: Symbolic Representation of Algorithms

  • 8/2/2019 02 Intro to Cpp

    41/101

    Flowchart: Symbolic Representation of Algorithms

    Flowchart: A graphic representation of an algorithm

    often used in the design phase of programming to work outthe logical flow of a program

    Uses symbols to represent each logical step of thealgorithm.

    The order in which the steps are carried out is indicated byconnecting flow lines

    Use a few, basic flowchart symbols

    Follow UML (Unified Modeling Language)

    Standard defined by OMG group:http://www.omg.org/technology/documents/formal/uml.htm

    Basic Flowchart

    http://www.omg.org/technology/documents/formal/uml.htmhttp://www.omg.org/technology/documents/formal/uml.htm
  • 8/2/2019 02 Intro to Cpp

    42/101

    Basic FlowchartSymbols

    Some basic symbols:

  • 8/2/2019 02 Intro to Cpp

    43/101

    Basic Control Structures

    a sequenceis a series of statements that execute one afteranother

    selection (branch) is used to execute different statements

    depending on certain conditions

    repetition (looping)is used to repeat statements whilecertain conditions are met.

    a subprogram (module) is used to break the program

    into smaller units

    SEQUENCE

  • 8/2/2019 02 Intro to Cpp

    44/101

    SEQUENCE

    Can contain any symbolexcept for the decision orloop symbol

    Steps are executed insequence with noinstruction changing theorder

    Flow lines connect eachinstruction

  • 8/2/2019 02 Intro to Cpp

    45/101

    SELECTION(branch)

    O ( )

  • 8/2/2019 02 Intro to Cpp

    46/101

    REPETITION (loop)

    Pseudocode

  • 8/2/2019 02 Intro to Cpp

    47/101

    Logical steps

    Written in English

    and symbols,

    terms, etc.

    Indenting forlogical structures

    begin some gamedisplay instructionspick a number between 1 and 100

    repeat turn until number is guessedor seven turns are completed

    input guess from userrespond to guess

    end repeat

    end some gamedisplay end message

    Looks like BASIC(Chris Clark)

    Pseudocode

    Pseudocode or three control

  • 8/2/2019 02 Intro to Cpp

    48/101

    Pseudocode or three controlconstructs

    What is Pseudocode?

  • 8/2/2019 02 Intro to Cpp

    49/101

    What is Pseudocode? An alternative to flowcharting

    Represents logic in an English-like manner Rules

    Avoid the use of words peculiar to a particular programminglanguage

    Indent lines to make the pseudocode easy to read andunderstand

    Show key words (Move, Write, Read) in a different color, font, orcapitalized

    Punctuation is optional

    End every If with EndIf Begin every loop with a Loop instruction; End every loop with

    EndLoop

    Main routine is to be shown first

    Terminate all routines with an End instruction (e.g., EndMain)

    Example 1

  • 8/2/2019 02 Intro to Cpp

    50/101

    Write an algorithm in pseudocode that findsthe average of two numbers

    Example 1

    SKIP: Average of two

  • 8/2/2019 02 Intro to Cpp

    51/101

    StartAverageOfTwo

    0. Input:Two numbers

    1. Add the two numbers2. Divide the result by 2

    3. Return the result by step 2

    End

    SKIP: Average of two

    Example 2

  • 8/2/2019 02 Intro to Cpp

    52/101

    Write an algorithm to change a numericgrade to a pass/no pass grade.

    Example 2

    SKIP: Pass/No Pass Grade

  • 8/2/2019 02 Intro to Cpp

    53/101

    Pass/NoPassGradeInput:One number

    1. if (the number is greater than or equal to 70)

    then

    1.1 Set the grade to passelse

    1.2 Set the grade to nopass

    End if

    2. Return the grade

    End

    SKIP: Pass/No Pass Grade

    Flowchart & Pseudocode

  • 8/2/2019 02 Intro to Cpp

    54/101

    Flowchart & Pseudocode

    Start

    Sum=0Count = 0

    InputGrade

    Moregrades?

    Sum = Sum + GradeCount = Count + 1

    Average = Sum/Count

    Stop

    No

    Yes

    FlowchartPseudocode

    BEGIN Average Gradesum=0count = 0

    DOINPUT gradeIF grade < 0 EXITsum = sum + gradecount = count +1

    END DOIF count > 0 THEN

    average = sum/countELSEaverage = 0

    END IFEND Average Grade

    Your first program in C++

  • 8/2/2019 02 Intro to Cpp

    55/101

    Your first program in C++

    hello.cpp compiler a.out

    Writing a program in Linux involves three steps

    e a s o a yp ca ++ nv ronmen

  • 8/2/2019 02 Intro to Cpp

    56/101

    e a s o a yp ca ++ nv ronmenPhases of C++ Programs:

    1. Edit2. Preprocess

    3. Compile

    4. Link

    5. Load & Execute LoaderPrimaryMemory

    Program is created in

    the editor and stored

    on disk.

    Preprocessor program

    processes the code.

    Loader puts program

    in memory.

    CPU takes each

    instruction and

    executes it, possibly

    storing new data

    values as the programexecutes.

    Compiler

    Compiler creates

    object code and stores

    it on disk.

    Linker links the object

    code with the libraries,

    creates a.out and

    stores it on disk

    Editor

    Preprocessor

    Linker

    CPU

    PrimaryMemory

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    Disk

    Disk

    Disk

    Disk

    Disk

    Code (write) the program

  • 8/2/2019 02 Intro to Cpp

    57/101

    Code (write) the program

    Carefully enter the code

    Remember most C++ statements end with a ;

    Commands are in lower case

    DEMO: 1 Edit

  • 8/2/2019 02 Intro to Cpp

    58/101

    DEMO: 1. Edit

    Start up an editor (emacs) to edit a file called hello.cpp

    Type the following into the file:

    #include

    using namespace std;

    int main(void){

    cout

  • 8/2/2019 02 Intro to Cpp

    59/101

    DEMO: 2. Compile

    Compile your program

    g++ hello.cpp

    This tells the computer to call the compiler tocreate the program

    The compiler is a program that takes the codethat you write and translates it into machine

    languageMachine code is made up of many simple

    instructions composed of 0s and 1s

    DEMO: 3 Execute

  • 8/2/2019 02 Intro to Cpp

    60/101

    DEMO: 3. Execute

    You should now have a file called a.out

    inside your directory

    This file is called an executablea.out holds the binary version of your code

    (the computer doesnt understand words, just0s and 1s)

    To run the program type:./a.out

    What does the code mean?

  • 8/2/2019 02 Intro to Cpp

    61/101

    What does the code mean?

    #include

    using namespace std;

    Allows us to use functions that other peoplehave written to facilitate input and output

    Processed by the pre-processor(its called apre-processor directive)

    Literally copies and pastes the libraries offunctions that others wrote

    This is what makes Java and MFC so powerful!

    What does the code mean?

  • 8/2/2019 02 Intro to Cpp

    62/101

    What does the code mean?

    int main(void)

    Remember, every C++ program is made of one ormore functions

    A functionis a piece of code that accomplishes onespecific task

    Every executable C++ program has one functioncalled main()

    This is where execution (the actual running) of theprogram (i.e., the computer instructions) starts

  • 8/2/2019 02 Intro to Cpp

    63/101

    What does the code mean?

    int main(void)

    When you type ./a.out to run the program you

    are essentially telling the computer to call thismain() function

    Callinga function means to execute the code inthe function

  • 8/2/2019 02 Intro to Cpp

    64/101

    What does the code mean?

    int main(void)

    The int is the return type of the function.

    In other words when it finishes what kind of result

    does it give back. A whole number? A character?int means a whole number.

    We want to give this number back to tell us if theprogram was sucessfully completed

  • 8/2/2019 02 Intro to Cpp

    65/101

    What does the code mean?

    int main(void)

    The void in the brackets is the parameter list

    for this function

    The parameter list indicates what this functionneeds to be given from the outset for it to work

    void indicates that we give nothing to this

    function.

    What does the code mean?

  • 8/2/2019 02 Intro to Cpp

    66/101

    What does the code mean?

    cout

  • 8/2/2019 02 Intro to Cpp

    67/101

    What does the code mean?

    return 0;

    This is the last line in our program

    It basically means that the program is now done

    return means to go back to where theprogram was called from0 is used to indicate that it was successfully

    completed (a general convention)

    What does the code mean?

  • 8/2/2019 02 Intro to Cpp

    68/101

    What does the code mean?

    Note also that the code of main() is containedwithin the { }

    These {} group code together.

    In this case it tells us that all the code between themare part of the main function

    #include

    using namespace std;

    int main(void){

    cout

  • 8/2/2019 02 Intro to Cpp

    69/101

    Some Important Terms A source program(.cpp file type) consists of the program statements

    comprising a C++ or other programming language program.

    An object program (.obj file type) is the result of compiling a source

    program.

    Header files (.h file type) contain constant, variable, and function

    declarations needed by a program.

    An executable program is a program that can be run by a computer. Linking adds code from libraries to your file. Collects the object code

    from all files in the workspace and puts them into one executableprogram.

    A compiler is a program that translates a source program into an

    object program. An interpreter is a program that translates individual source program

    statements, one at a time, into executable statements. Each statementis executed immediately after translation.

    Compiling / Building

  • 8/2/2019 02 Intro to Cpp

    70/101

    Compiling / Building

    (.cpp file)source code

    compiler

    (.obj file)

    object code

    (.h files)

    linked tolibraries

    executable

    file

    object code fromother source files

    Error error does not compute!

  • 8/2/2019 02 Intro to Cpp

    71/101

    Error, error does not compute! Syntax Errors Typing Errors

    Errors in spelling and grammar (syntax). Doag. Bites, Man

    You can use the compiler or interpreter to uncover syntaxerrors.

    You must have a good working knowledge of error messagesto discover the cause of the error.

    Semantic Errors Logic or Meaning Errors Errors that indicate the logic used when coding the program

    failed to solve the problem. Man bites dog.

    You do not get error messages with logic errors. Your only clue to the existence of logic errors is the

    production of wrong solutions.

    Run-time Errors (Exceptions) Code does something illegal when it is run (hence runtime)

    E.g., divide by zero

    Syntax refers to the structure of a program and

    the rules about that structure

    Procedural

  • 8/2/2019 02 Intro to Cpp

    72/101

    programming producedsignificantimprovements insoftware quality anddevelopment time

    SoWhy are Programmers Now Using

  • 8/2/2019 02 Intro to Cpp

    73/101

    SoWhy are Programmers Now UsingObject-Oriented Programming?

    Increasing dependence on informationprocessing is creating a crisis

    Volume of information is increasingfaster than the ability to create software

    Programmers cannot generate softwareto keep pace with the potential of newhardware

    Some Programming Issues are Not

  • 8/2/2019 02 Intro to Cpp

    74/101

    g gAdequately Addressed by ProceduralProgramming

    It is rarely possible to anticipate the design of a completedsystem before its actually implemented

    Systems are works in progress

    Development of GUIs is very complicated in traditionalprocedure-oriented programming languages

    Sharing data across routines is difficult and error-prone

    Focus of structured programming is on the modularity andprocedures

    Data interactions are ignored Allowing modules to share all their data and interact freely

    creates subroutines that are very dependent on each other--therefore, we dont have independent routines

    So, Whats the Answer to theD t Sh i P bl ?

  • 8/2/2019 02 Intro to Cpp

    75/101

    ,Data Sharing Problem?

    Modularize the data along with the procedures bygiving each subroutine its own local data that italone can read and write

    INFORMATION

    HIDING

    Information Hiding Allows theP t W k ith M d l

  • 8/2/2019 02 Intro to Cpp

    76/101

    Programmer to Work with Modules orProcedures Developed by Others at an

    Abstract Level Abstraction

    Internal details are hidden from the user

    Data and procedures are not exposed toprocedures not needing to know them

    Another Advantage of Object

  • 8/2/2019 02 Intro to Cpp

    77/101

    Another Advantage of Object-Oriented Programming is

    Reusability Building a house

    Electrical system

    Plumbing system

    Heating/airconditioningsystem

    Objects in Windows

    Buttons Menus

    Fields

    ow roce ura rogramm ng oo s a aProblem

  • 8/2/2019 02 Intro to Cpp

    78/101

    Problem

    Procedures

    Data acted upon by the procedures aremaintained separately from the procedures

    Data assumes a secondary role!

    Program

    Procedure

    Procedure Data

    ow ec - r en e rogramm ngLooks at a Problem?

  • 8/2/2019 02 Intro to Cpp

    79/101

    Looks at a Problem?

    Objects

    Data

    Methods

    Scope Methods surround

    the data andprotect data from

    other objects Encapsulation and

    InformationHiding!

    Data

    Objects

  • 8/2/2019 02 Intro to Cpp

    80/101

    j

    Objects are things (nouns)

    Objects have attributes (properties)Adjectives that describe an object

    Objects have methods (behaviors)

    Verbs that specify what the object can do Events are used to trigger behaviors

    Objects interact with each other by passingmessages amongst themselves

    Why Do We till Write ProceduralPrograms?

  • 8/2/2019 02 Intro to Cpp

    81/101

    yPrograms?

    Way of breaking a program into routines

    Object-oriented programming works at ahigher level of abstraction than procedural

    programming does After objects have been identified, methods

    are designed using procedural techniques

    We are concentrating on methods or

    procedures

  • 8/2/2019 02 Intro to Cpp

    82/101

    Common Business-OrientedLanguage (COBOL)

  • 8/2/2019 02 Intro to Cpp

    83/101

    Sample Cobol program

    Language (COBOL) COBOL:

    The earliest (1959)high-level language

    The most widelyused businesslanguage

    A proven way to doaccounting,inventory, billing, and

    payroll

    Requiresprogrammers toexplain what the

    program is doing at

    Formula Translator (Fortran)

  • 8/2/2019 02 Intro to Cpp

    84/101

    Sample Fortran program

    Formula Translator(Fortran) Fortran:

    Began in the 1950sIs suited toscientific,mathematical, and

    engineeringapplications

    Is used to solvecomplex equations

    Features simplicity,economy, and easeof use

    Ada

  • 8/2/2019 02 Intro to Cpp

    85/101

    Sample Ada program

    Ada

    Ada:

    Named afterAugusta Ada Byron

    Incorporatesmodularprogramming

    The requiredlanguage for theU.S. Defense

    DepartmentSuitable for control

    of real-timesystems (missiles)

    Beginners All-Purpose SymbolicI t ti C d (BASIC)

  • 8/2/2019 02 Intro to Cpp

    86/101

    Sample BASIC program

    g p yInstruction Code (BASIC)

    BASIC:

    An easy-to-use language available on personalcomputers

    Widely taught in schools as a beginners

    programming language

    Designed as an interpreted language

    Visual Basic (VB)

  • 8/2/2019 02 Intro to Cpp

    87/101

    Visual Basic (VB)

    Visual Basic:Is widely used inprogram developmentpackages

    Uses event-drivenprogramming

    Enables theprogrammer to developan application by usingon-screen graphical userinterfaces

    Sample Visual Basic

    Sample Pascal programPascal

  • 8/2/2019 02 Intro to Cpp

    88/101

    Sample Pascal program

    Pascal:

    Is named after Blaise Pascal

    Encourages programmers to write well-structured

    programs

    Widely accepted as a teaching language

    Has been updated to reflect new approaches to

    programming

    C

  • 8/2/2019 02 Intro to Cpp

    89/101

    Sample C program

    C C:

    Was developed byAT&Ts Bell Labs in

    the 1970s Combines high-

    level programming

    language withassembly language

    Programmersmanipulate bits ofdata within a

    processing unit

    Difficult to learn andprogramming is time

    consuming

    Smalltalk

  • 8/2/2019 02 Intro to Cpp

    90/101

    Sample Smalltalk program

    Smalltalk:Developed in the 1970s by

    Xerox Corp

    100% pure object-

    oriented programminglanguage

    Not often chosen forsoftware development

  • 8/2/2019 02 Intro to Cpp

    91/101

    C++ C++:

    Incorporates object-oriented features

    Is widely used for

    professional programdevelopment

    Sample C++ program

    Java

  • 8/2/2019 02 Intro to Cpp

    92/101

    Java

    Java:Developed by Sun Microsystems

    An object-oriented, high-level

    programming language with a twistFirst true cross-platform

    programming language

    Gained acceptance faster than any

    other programming languageA simplified version of C++

  • 8/2/2019 02 Intro to Cpp

    93/101

    Java

    Java, continued :

    Java is designed to run on any computer platform

    Java Virtual Machine enables cross-platformuse

    Java applets or small programs are downloadedto computers through networks

    Weaknesses include:The security risk in downloading applets

    The speed in running the programs

    Sample Java Program

  • 8/2/2019 02 Intro to Cpp

    94/101

    p g

    Web-Based Languages

  • 8/2/2019 02 Intro to Cpp

    95/101

    Web Based Languages Markup languages:

    Hypertext markup language (HTML) sets theattributes of text and objects within a Web page

    Extensible markup language (XML) is used forsharing data and objects in a Web environment

    Scripting languages:

    VBScript is used to write short programs (scripts)that are embedded in Web pages

    JavaScript is used to write scripts on Web pages

    Visual Studio .NET:

    Used forthe development of scripts andprograms that are accessible from the Web

    The Programming Life Cycle

  • 8/2/2019 02 Intro to Cpp

    96/101

    The Programming Life Cycle

    Define the problem

    Make or buy software?

    Design the program by making an algorithm

    Code (write) the program

    Document the program

    Compile and execute the program

    Syntax and run time errors Test (debug) the program

    Logic errors

    Summary

  • 8/2/2019 02 Intro to Cpp

    97/101

    Summary A programming language is an artificial language

    consisting of a vocabulary and a set of rules Machine language is the lowest-level programming

    language

    Assembly language contains symbols for

    programming instructions Third-generation (high-level) languages require

    programmers to specify the procedures to be followed

    Object-oriented languages combine procedures anddata

    Summary continued

  • 8/2/2019 02 Intro to Cpp

    98/101

    Summary, continued

    The SDLCs six phases are:

    Defining the program

    Designing the program

    Coding the program

    Testing, debugging, and formalizing the program Implementing and maintaining the program

    Top-down programming makes programs easier to debugand maintain

    Debugging requires finding and correcting syntax errorsand logic errors

    Flowcharts for the three constructs

  • 8/2/2019 02 Intro to Cpp

    99/101

    Alternative ontrol tructureFlowcharts

  • 8/2/2019 02 Intro to Cpp

    100/101

    Flowcharts Sequence

    Selection Repetition (Looping)

    Pseudocode! What is pseudocode?

    P d d i b i ll h t E li h h d t l i ifi t k ithi ' l ith

  • 8/2/2019 02 Intro to Cpp

    101/101

    Pseudocode is basically short, English phrases used to explain specific tasks within a program's algorithm.

    Pseudocode should not include keywords in any specific computer languages.

    Indentation can be used to show the logic in pseudocode as well.

    Why is pseudocode necessary?

    Writing pseudocode WILL save you time later during the construction & testing phase of a program'sdevelopment lets you think out the program before you code it.

    How do I write pseudocode?

    Consists mainly of executablestatements

    Original Program Specification:Write a program that obtains two integer numbers from the user.

    It will print out the sum of those numbers.

    Variables required (names and types):int1: (integer) to store first integerint2: (integer) to store the second integersum: (integer) to store the sum of the numbers

    Pseudocode:Prompt the user to enter the first integer int1Prompt the user to enter a second integer int2Compute the sum of the two user inputs sum = int1 + int2Display an output prompt that explains the answer

    If you cant write it in pseudocode, you

    wont be able to write it in C++!