You are on page 1of 101

Intro to C++

Lecture 2

Programming Languages
Machine Language Fortran COBOL Visual Basic Smalltalk

Assembly Language Pascal

BASIC
C and C++

Ada
Java

Programming languages are artificial languages created 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 an organized method of software development

C++ Predecessors

Early procedural languages included


FORTRAN:

Formula Translation ALGOL: Algorithmic Language COBOL: Common Business Oriented Language BASIC: Beginners All-purpose Symbolic Instruction Code Pascal C Smalltalk, Simula, etc. were the object-oriented predecessors of C++

Third-Generation and FourthGeneration (High-Level) Languages

The Evolution of Programming Languages

First-Generation Languages

Machine language:
Consists Is

of binary numbers (0s and 1s)

the earliest programming language Is the only language the computer understands without translation
It

is machine dependent; each family of processors has its own machine language

Second-Generation Languages
Assembly language: Resembles machine language Is a low-level language Uses brief abbreviations for program instructions.
Abbreviations are called

mnemonics
A program is written in

source code (text file) and translated into machine language by an assembler

Third-Generation Languages

Procedural languages:
Are

high-level languages that tell the computer what to do and how to do it Create programs at a high level of abstraction Are easier to read, write, and maintain than machine and assembly languages Use a compiler or interpreter to translate code Fortran and COBOL are third-generation languages

Compilers and Interpreters

An interpreter translates source code one line at a time and executes the instruction A compiler is a program that changes source code to object code, all in one shot Example of an interpreted language: BASIC; a compiled language: C

The Great Software Crisis of the 60s

Spaghetti Code and the Great Software Crisis: goto statements resulted in programs that were difficult to follow This made them difficult to modify, maintain, and even develop! This problem led to the software crisis of the 1960s
Programs

were not ready on time Programs exceeded their budgets Programs contained too many errors Customers were not satisfied Management was also very frustrated!

Structured Programming to the rescue

Structured programming languages: Were developed to improve software development Include Algol and Pascal Are well-structured and organized Forbid the use of goto statements
Use

three fundamental control structures


Selection, Repetition

Sequence,

Modular Programming Languages developed in the 70s

Modular programming languages: Were developed because of problems in structured programming languages Are used to create programs that are divided into separate modules
Each

module carries out a special function

Require

specified input to produce specified

output

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 program to generate the report) Languages for getting information out of databases (generate a program to process a query or generate a form) More ambitious 4GL environments attempt to automatically generate whole systems from the outputs of CASE tools, specifications of screens and reports, and possibly also the specification of some additional processing logic, including data flow diagrams, entity relationship diagrams, entity life history diagrams

Query languages

Also include visually-oriented languages

Fifth-generation languages These include artificial intelligence and neural networks oriented languages

SKIP: Object-Oriented Programming


Object-oriented programming (OOP):
Relies on component reusability The ability to produce program modules that perform a specific task Eliminates the distinction between programs

and data Uses objects that contain data and procedures

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 objects Objects near the bottom are narrower in scope Inheritance refers to an objects capacity to pass on its characteristics to its subclasses

Programming Language Classification


Computer languages (not just programming languages!) can be classified into two general categories: Imperative and Declarative Imperative languages include:

Generic/General Programming Languages

They allow user-defined data types, data abstraction, polymorphism, etc.

Procedural Programming Languages Object-Oriented Programming Languages Functional Programming Languages (e.g., Haskell, Scheme, etc.) Logical Programming Languages (e.g., Prolog) Even Markup Languages like HTML

Declarative languages include:

Theyre not programming languages because they dont allow for the three fundamental control structures but they do declare what pages should look like, etc.

Procedural Programming (structured and modular):

An important methodology for dealing with complexity is structured programming Structured Programming requires well-organized, structured code that uses the three fundamental control structures (sequence, selection, repetition) Complex tasks need to be broken down into simpler subtasks this is modular programming Procedural programming reduces complex problems to collections of simple, interconnected modules it combines structured and modular programming!

It is up to the programmer to implement procedural programming

3GL Programming Languages

Most high-level programming languages can be categorized into one of three main categories:
Procedural

Languages (FORTRAN, BASIC, COBOL, Pascal, etc.) Object-Oriented Languages (Smalltalk, Effiel, etc.) Hybrid Languages allow both OO and Procedural (such as C++)

3GL vs. 4GL

3GL: Procedure-oriented (structured) languages

Programmers concentrate on the procedures used in the program

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

3GL: Object-oriented languages

Items are represented using self-contained objects

Can be used to create programs for graphical windows environments

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 .

Procedural Programming Basics

The purpose of most application programs is to process data to produce specific results

Basic procedural operations.

What Can a Procedural Program Do?

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


Read

Input Calculate Store data Write Output Work in a sequential progression (Sequence) Compare and branch (Selection) Iterate or Loop (Repetition)

Advantages of Procedural Programming

Easier to test and debug

Structured walkthroughs of the code


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

goto-less

Standard method for solving a problem A single program can be written by more than one programmer

By dividing the program up into modules

Programs can share routines (again, because of modularization)

Whats structured programming?

A Structure is One or More Instructions (Flowchart Symbols) Combined According to Rules

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

What Are the Rules for Writing a Structured Program?


3 basic control structures:

Sequence Selection (decision) Repetition (looping or iteration)

Modularization

Modular Program: a program consisting of interrelated segments arranged in a logical and understandable form
Easier

to develop, correct, and modify than other kinds of programs

Module: a small segment which is designed to perform a specific task A group of modules is used to construct a modular program

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 Routine does one function such as printing
Instructions are closely related

Strong cohesion

Loose coupling

Non-existent or weak connection between routines


One routine does not depend on other routines

SUBPROGRAM (function)
SUBPROGRAM1
...

SUBPROGRAM1 a meaningful collection of SEQUENCE, SELECTION, REPETITION (LOOP), or SUBPROGRAMS

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 encapsulated and hidden within the function

A Multiplying Function

Classes and Functions

Function: encapsulates a set of operations, while a class encapsulates 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 Software Development Life Cycle (SDLC)

The SDLC was introduced in the 1970s to address problems in creating programs It provides an organized plan for breaking down the task 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

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

Phase 2: Designing the Program

Programmers create the programs design Top-down design focuses on the programs main goal (main routine), then breaks the program into manageable components (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 description of 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

Structured Design

Structured programming implements structured design Control structures are logical constructs that specify how the instructions in a program are to be executed Three fundamental types of control structures: Sequence control structure Instructions are executed in the order in which they appear Selection control structures The program branches to different instructions depending on whether a condition is met; IFTHENELSE Repetition control structure The program repeats the same instructions over and over; DOWHILE and DO-UNTIL

Structure Chart and Flowchart


Structure Chart

Flowchart

Phase 3: Coding the Program

Coding requires the translation of the algorithm into specific program instructions An appropriate programming language is chosen, and the code is typed according to its syntax rules Documentation is created for future use

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

The variable names and definitions, a description of the files needed, and the layout of the output are produced A user manual is developed to explain how the program works

Phase 4: Testing and Debugging the Program


Testing and debugging eliminate all errors Syntax and logic errors are corrected Debugging is the process of eliminating errors

Phase 5: Implementing and Maintaining the Program

The program is:


Tested

by users Thoroughly documented Maintained and evaluated regularly

Algorithms

Algorithm: A step-by-step sequence of instructions that must terminate


Pseudocode
Use

of English-like phrases to describe an algorithm

Formula
Use

of mathematical equations to describe an algorithm of diagrams that employ symbols to describe an algorithm

Flowchart
Use

Program Design Process


Algorithm Design (underlying logic of program)

AL-KHOWARIZMI

Program Composition

Debug & test (error free & reliable)

Documentation

Maintenance

75% of costs!

Grace M. Hopper

First Bug

Whats an Algorithm?

A predetermined series of instructions for carrying out a task in a finite number of steps I.e., Baking A Cake! Two commonly used tools to help document the program logic (the algorithm): Flowcharts and Pseudocode. Generally, Flowcharts work well for small problems but Pseudocode is used for larger problems

How to make a plan ?

Do a hand calculation (brainstorming!)


Make a flowchart
Visio

or dia

Write the Pseudocode

Flowchart: Symbolic Representation of Algorithms

Flowchart: A graphic representation of an algorithm

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

Uses symbols to represent each logical step of the algorithm. The order in which the steps are carried out is indicated by connecting 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 Symbols

Some basic symbols:

Basic Control Structures

a sequence is a series of statements that execute one after another


selection (branch) is used to execute different statements depending on certain conditions repetition (looping) is used to repeat statements while certain conditions are met.

a subprogram (module) is used to break the program into smaller units

SEQUENCE

Can contain any symbol except for the decision or loop symbol Steps are executed in sequence with no instruction changing the order Flow lines connect each instruction

SELECTION (branch)

REPETITION (loop)

Pseudocode
Logical steps
Written in English and symbols, terms, etc.
begin some game display instructions pick a number between 1 and 100

Indenting for logical structures


Looks like BASIC (Chris Clark)

repeat turn until number is guessed or seven turns are completed input guess from user respond to guess end repeat
end some game display end message

Pseudocode for three control constructs

What is Pseudocode?

An alternative to flowcharting Represents logic in an English-like manner Rules


Avoid the use of words peculiar to a particular programming language Indent lines to make the pseudocode easy to read and understand Show key words (Move, Write, Read) in a different color, font, or capitalized 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
Write an algorithm in pseudocode that finds the average of two numbers

SKIP: Average of two

0. 1. 2. 3.

StartAverageOfTwo Input: Two numbers Add the two numbers Divide the result by 2 Return the result by step 2 End

Example 2
Write an algorithm to change a numeric grade to a pass/no pass grade.

SKIP: Pass/No Pass Grade


Pass/NoPassGrade Input: One number 1. if (the number is greater than or equal to 70) then 1.1 Set the grade to pass else 1.2 Set the grade to nopass End if 2. Return the grade End

Flowchart & Pseudocode


Flowchart
Start

Pseudocode
Sum=0 Count = 0 BEGIN Average Grade sum=0 count = 0 DO INPUT grade IF grade < 0 EXIT sum = sum + grade count = count +1 END DO IF count > 0 THEN average = sum/count ELSE average = 0 END IF END Average Grade

Sum = Sum + Grade Count = Count + 1

Input Grade

Yes

More grades? No

Average = Sum/Count

Stop

Your first program in C++

Writing a program in Linux involves three steps

hello.cpp

compiler

a.out

Details of a Typical C++ Environment


Phases of C++ Programs:
1. Edit 2. Preprocess 3. Compile 4. Link 5. Load & Execute
Editor Disk

Program is created in the editor and stored on disk. Preprocessor program processes the code. 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

Preprocessor

Disk

Compiler

Disk

Linker

Disk
Primary Memory

Loader

Disk

Loader puts program in memory.


. . . . . .

Primary Memory

CPU

. . . . . .

CPU takes each instruction and executes it, possibly storing new data values as the program executes.

Code (write) the program


Carefully enter the code
Remember most C++ statements end with a ;

Commands are in lower case

DEMO: 1. Edit

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

Type the following into the file:

#include <iostream> using namespace std; int main(void){ cout << Hello World << endl; return 0; }

DEMO: 2. Compile

Compile your program


g++

hello.cpp

This

tells the computer to call the compiler to create the program

The

compiler is a program that takes the code that you write and translates it into machine language Machine code is made up of many simple instructions composed of 0s and 1s

DEMO: 3. Execute

You should now have a file called a.out inside your directory
This

file is called an executable a.out holds the binary version of your code (the computer doesnt understand words, just 0s and 1s)
To

run the program type:

./a.out

What does the code mean?

#include <iostream> using namespace std; Allows us to use functions that other people have written to facilitate input and output
by the pre-processor (its called a pre-processor directive) Literally copies and pastes the libraries of functions that others wrote This is what makes Java and MFC so powerful!
Processed

What does the code mean?

int main(void)
Remember, every C++ program is made of one or more functions

A function is a piece of code that accomplishes one specific task

Every executable C++ program has one function called main()

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

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 this main() function
Calling

a function means to execute the code in the function

What does the code mean?

int main(void)
The
In

int is the return type of the function.

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 the program was sucessfully completed

What does the code mean?

int main(void)
void in the brackets is the parameter list for this function The parameter list indicates what this function needs to be given from the outset for it to work void indicates that we give nothing to this function.
The

What does the code mean?

cout << Hello World << endl;


This

line tells the computer to print something to the screen If you want to print something to the screen you use the cout function The endl adds an end line and flushes the buffer

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 the program was called from
0

is used to indicate that it was successfully completed (a general convention)

What does the code mean?

Note also that the code of main() is contained within the { } These {} group code together. In this case it tells us that all the code between them are part of the main function
#include <iostream>
using namespace std; int main(void){ cout << Hello World << endl; return 0; }

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 executable program. 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 statement is executed immediately after translation.

Compiling / Building
(.cpp file)

source code
(.h files)

compiler
(.obj file)

object code
object code from other source files

linked to libraries
executable file

Error, error does not compute!

Syntax Errors Typing Errors

Syntax refers to the structure of a program and the rules about that structure

Errors in spelling and grammar (syntax).


Doag. Bites, Man

You can use the compiler or interpreter to uncover syntax errors. You must have a good working knowledge of error messages to 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

Procedural programming produced significant improvements in software quality and development time

SoWhy are Programmers Now Using Object-Oriented Programming?


Increasing dependence on information processing is creating a crisis Volume of information is increasing faster than the ability to create software Programmers cannot generate software to keep pace with the potential of new hardware

Some Programming Issues are Not Adequately Addressed by Procedural Programming

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

Systems are works in progress

Development of GUIs is very complicated in traditional procedure-oriented programming languages Sharing data across routines is difficult and error-prone
Focus of structured programming is on the modularity and procedures 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 the Data Sharing Problem?

Modularize the data along with the procedures by giving each subroutine its own local data that it alone can read and write

INFORMATION HIDING

Information Hiding Allows the Programmer to Work with Modules or Procedures Developed by Others at an Abstract Level

Abstraction Internal details are hidden from the user Data and procedures are not exposed to procedures not needing to know them

Another Advantage of ObjectOriented Programming is Reusability

Building a house
Electrical system Plumbing system Heating/air conditioning system

Objects in Windows
Buttons Menus Fields

How Procedural Programming Looks at a Problem


Procedures Data acted upon by the procedures are maintained separately from the procedures Data assumes a secondary role! Program
Procedure

Data

Procedure

How Object-Oriented Programming Looks at a Problem?

Objects
Data Methods Scope

Methods surround the data and protect data from other objects Encapsulation and Information Hiding!

Data

Objects

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 passing messages amongst themselves

Why Do We Still Write Procedural Programs?


Way of breaking a program into routines Object-oriented programming works at a higher 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

Common Business-Oriented Language (COBOL)

COBOL: The earliest (1959) high-level language The most widely used business language A proven way to do accounting, inventory, billing, and payroll Requires programmers to explain what the program is doing at

Sample Cobol program

Formula Translator (Fortran)

Fortran: Began in the 1950s Is suited to scientific, mathematical, and engineering applications Is used to solve complex equations Features simplicity, economy, and ease of use

Sample Fortran program

Ada

Ada: Named after Augusta Ada Byron Incorporates modular programming The required language for the U.S. Defense Department Suitable for control of real-time systems (missiles)

Sample Ada program

Beginners All-Purpose Symbolic Instruction Code (BASIC)


Sample BASIC program

BASIC: An easy-to-use language available on personal computers Widely taught in schools as a beginners programming language Designed as an interpreted language

Visual Basic (VB)


Sample Visual Basic

Visual Basic: Is widely used in program development packages Uses event-driven programming Enables the programmer to develop an application by using on-screen graphical user interfaces

Pascal

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: Was developed by AT&Ts Bell Labs in the 1970s Combines highlevel programming language with assembly language Programmers manipulate bits of data within a processing unit

Sample C program

Difficult

to learn and programming is time consuming

Smalltalk
Sample Smalltalk program

Smalltalk: Developed in the 1970s by Xerox Corp 100% pure objectoriented programming language Not often chosen for software development

C++

C++: Incorporates objectoriented features Is widely used for professional program development

Sample C++ program

Java

Java: Developed by Sun Microsystems An object-oriented, high-level programming language with a twist First true cross-platform programming language Gained acceptance faster than any other programming language A simplified version of C++

Java

Java, continued :
Java

is designed to run on any computer platform Java Virtual Machine enables cross-platform use Java applets or small programs are downloaded to computers through networks Weaknesses include:
The

security risk in downloading applets The speed in running the programs

Sample Java Program

Web-Based Languages

Markup languages: Hypertext markup language (HTML) sets the attributes of text and objects within a Web page Extensible markup language (XML) is used for sharing 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 for the development of scripts and programs that are accessible from the Web

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

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 and data

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 debug and maintain Debugging requires finding and correcting syntax errors and logic errors

Flowcharts for the three constructs

Alternative Control Structure Flowcharts


Sequence Selection Repetition (Looping)

What is pseudocode?

Pseudocode!

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. Writing pseudocode WILL save you time later during the construction & testing phase of a program's development lets you think out the program before you code it. Consists mainly of executable statements

Why is pseudocode necessary?

How do I write pseudocode?

If you cant write it in pseudocode, you wont be able to write it in C++!

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 integer int2: (integer) to store the second integer sum: (integer) to store the sum of the numbers

Pseudocode: Prompt the user to enter the first integer int1 Prompt the user to enter a second integer int2 Compute the sum of the two user inputs sum = int1 + int2 Display an output prompt that explains the answer Display the result

You might also like