Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Chapter 2

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 59

CHAPTER 2:

Introduction to Programming

1
Outline
1. Introduction to computer
programming
2. Types programming language ?
3. Interpreting vs. Compiling
4. Problem solving Techniques
5. Mechanics of creating a program
and basics of C++ environment
1. Introduction to computer
programming
Discussion

• What is Computer Program ?


Computer Programs
The terms computer programs,
software programs, or just programs
are the instructions that tells the
computer what to do.
Sets of instructions that control a
computer’s processing of data
 Computer requires programs to
function, and a computer programs does
nothing unless its instructions are
executed by a CPU.
Discussion

• What is Programming ?
Programming
 is the process of writing, testing,
debugging / troubleshooting, and
maintaining the source code of
computer programs.
 Writing computer programs means
writing instructions, that will make the
computer follow and run a program
based on those instructions.
 Computer programs (also know as source
code) is often written by professionals
known as Computer Programmers
Many Aspects of Programming
• Programming is problem solving
– always trying to make computer do something useful — i.e., finding an optimal travel
route
• Programming is controlling
– computer does exactly what you tell it to
• Programming is teaching
– computer can only “learn” to do new things if you tell it how
• Programming is creative
– must find a good solution out of many possibilities
• Programming is modeling
– describe salient (relevant) properties and behaviors of a system of components (objects)
• Programming is abstraction
– identify important features without getting lost in detail
Discussion

• What is Programming
Language ?
Programming language
• It is a set different category of written symbols
that instruct computer hardware to perform
specified operations required by the designer.
• an artificial language that can be used to control the
behavior of a computer
• A main purpose of programming languages is to
provide instructions to a computer.
• Programming languages have many similarities with
natural languages e.g., they conform to rules for
syntax and semantics, there are many dialects, etc.
---cont
• But programming languages differ from most
other forms of human expression in that they
require a greater degree of precision and
completeness.
• When using a natural language to communicate
with other people, human authors and speakers can
be ambiguous and make small errors, and still
expect their intent to be understood.
• However, computers do exactly what they are told
to do, and cannot understand the code the
programmer "intended" to write.
---cont
• Every programming languages have syntax and
semantics
• defined by
– Syntactic - describes the possible combinations of
symbols that form a syntactically correct program
– Semantic - The meaning given to a combination of
symbols
• In every programming Language there are sets of
rules that govern the symbols used in a programming
language.
• These set of rules determine how the programmer can
make the computer hardware to perform a specific
operation. These sets of rules are called syntax.
Some Well-Known Programming
Languages
C++
BASIC Ruby
FORTRAN
Java
Visual Basic
COBOL C#
JavaScript
C Python
2. Types of programming language
• Available programming languages come
in a variety of forms and types.
Thousands of different programming
languages have been developed, used,
and discarded.
• Programming languages can be divided
in to two major categories:
– low-level languages and
– high-level languages.
Low-level languages
• Machine language
– Computers only understand one language and that is
binary language or the language of 1s and 0s.
– Binary language is also known as machine language, one
of low-level languages.
– In the initial years of computer programming, all the
instructions were given in binary form.
– Although the computer easily understood these programs,
it proved too difficult for a normal human being to
remember all the instructions in the form of 0s and 1s.
– Therefore, computers remained mystery to a common
person until other languages such as assembly language
was developed, which were easier to learn and understand
---A. Low-level languages
• Assembly language
– correspondences symbolic instructions and executable machine
codes and was created to use letters (called mnemonics) to each
machine language instructions to make it easier to remember or write.
For example:
• ADD A, B – adds two numbers in memory location A and B
– Assembly language is nothing more than a symbolic representation
of machine code, which allows symbolic designation of memory
locations.
– However, no matter how close assembly language is to machine code,
computers still cannot understand it. The assembly language must be
translated to machine code by a separate program called assembler.
– The machine instruction created by the assembler from the original
program (source code) is called object code.
– Thus assembly languages are unique to a specific computer (machine).
– Assemblers are written for each unique machine language.
---A. Low-level languages
• Assembly language
– The machine instruction created by the assembler
from the original program (source code) is called
object code.
– Thus assembly languages are unique to a specific
computer (machine).
– Assemblers are written for each unique machine
language.
– Although programming in assembly language is not
as difficult and error prone as stringing together ones
and zeros, it is slow and cumbersome.
– In addition it is hardware specific.
B. High-level languages
• The lack of portability between different computers
led to the development of high-level languages—so
called because they permitted a programmer to ignore
many low-level details of the computer's hardware.
• Further, it was recognized that the closer the syntax,
rules, and mnemonics of the programming language
could be to "natural language" the less likely it became
that the programmer would inadvertently introduce
errors (called "bugs") into the program.
• High-level languages are more English-like and,
therefore, make it easier for programmers to
"think" in the programming language.
----- B. High-level languages
• High-level languages also require translation to machine
language before execution.
• This translation is accomplished by either a compiler or
an interpreter.
• Compilers translate the entire source code program
before execution.
• Interpreters translate source code programs one line at
a time.
• Interpreters are more interactive than compilers.
• FORTRAN (FORmula TRANs,ator), BASIC (Bingers
All Purpose Symbolic Instruction Code), PASCAL, C,
C++, Java are some exa-ples of high-level languages.
Low level vs High level
– low-level
• provide little or no abstraction, e.g., machine code and assembly
language
– Difficult to use
– Allows to program efficiently and with a low memory footprint
• used for communication with computer hardware directly.
• Often written in binary machine code (0’s/1’s) directly.
• machine specific or dependent.

– high-level
• closer to human languages
• isolate the execution semantics of a computer architecture from the
specification of the program
• Simplifies program development
• are machine independent and can run on variety of computers.
4. Problem solving Techniques
• Problem solving is the process of transforming the description of
a problem into the solution by using our knowledge of the
problem domain and by relying on our ability to select and use
appropriate problem-solving strategies, techniques, and tools.
• Problem solving, or breaking down the solution to a problem into
sequential steps is by far the most difficult part of computer
programming.
• A problem is an undesirable situation that prevents the organization
from fully achieving its purpose, goals and objectives.
• Or problem can also be defined as the gap between the existing
and the desired situation where problem solving will try to fill this
gap.
---cont
• Computer solves varieties of problems that can be expressed
in a finite number of steps leading to a precisely defined
goal by writing different programs.
• A program is not needed only to solve a problem but also it
should be reliable, (maintainable) portable and efficient.
• In computer programming two facts are given more weight:
– The first part focuses on defining the problem and logical
procedures to follow in solving it.
– The second introduces the means by which programmers
communicate those procedures to the computer system so that it
can be executed.
---cont
• There are system analysis and design tools, that can be
used t/ define the problem in terms of the steps to its
solution. The programmer uses programming language
to communicate the logic of the solution to the
computer.
• Before a program is written, the programmer must
clearly understand what data are to be used, the desired
result, and the procedure to be used to produce the result.
• The procedure, or solution, selected is referred to as
an algorithm.
5.1 Algorithm
• An algorithm is defined as a step-by-step sequence of
instructions that must terminate and describe how the
data is to be processed to produce the desired outputs.
• Simply, algorithm is a sequence of instructions.
• Algorithms are a fundamental part of computing.
There are three commonly used tools to help to
document program logic (the algorithm). These are
flowcharts, structured chart, and Pseudocode. We
will use the three methods here.
• Generally, flowcharts work well for small problems
but Pseudocode is used for larger problems.
Example Algorithm for Calculating
Gross Pay
5.1.1 Pseudocode
• Is an artificial and informal language that
helps programmers develop algorithms
• Allows the designer to focus on the logic of
the algorithm without being distracted by
details of language syntax
• text-based" detail (algorithmic) design tool
• Pseudocode is not a rigorous notation, since
it is read by other people, not by the
computer
Words that can be used for:
•Computation/Assignment 
– set the value of "variable" to :"arithmetic expression" or
        "variable" equals "expression" or
        "variable" = "expression"
•Input/Output
–    get "variable", "variable", ...
   display "variable", "variable", ...
•Conditional
–          if  "condition"
                   (subordinate) statement 1 
                     etc ...
       else
                    (subordinate) statement 2
                    etc ...
•Iterative
–           while "condition" 
                    (subordinate) statement 1
                   etc ...
• Examples:
– Write a program that prints “passed” when the student
garde is greater than 60 and “failed” otherwise.
• If student's grade is greater than or equal to 60
– Print "passed"
• else
– Print "failed“
– Pseudo-code the task of computing the final price of an
item after figuring in Value Added Tax(VAT) rate. Note
the three types of instructions: input (get),
process/calculate (=) and output (display)
1. start
2. get price of item
3. get sales tax rate (VAT)
4. sales tax = price of item times sales tax rate
5. final price = price of item plus sales tax
6. display final price
7. stop
• Variables: price of item, sales tax rate, sales tax,
final price
5.1.2 Flow Chart
• Algorithm could be designed using many techniques and tools.
• One tool of designing algorithm is by using flowcharts.
• Flowchart is a graphical way of expressing the steps needed
to solve a problem.
• A flow chart is a schematic (diagrammatic description)
representation of a process.
• A graphic representation of an algorithm, often used in the
design phase of programming to work out the logical flow of a
program
Flowchart symbols
Control Structures
• programs could be written in terms of 3
structures:
– Sequence – which instruction should be done
next?
– Selection – select between options
– Repetition – repeat an action while a given
condition stays true
Sequence: Executing instructions one after another as they appear
in the program.
.
Start

Input first num

Input second num

Sum=first num + second num

avg=sum/2

Output sum

Output avg

End
Selection
• Diamond symbol (decision symbol)
– Indicates decision is to be made
True print
– Contains an expression that can be true Grade>=60 passed
or false
– Test the condition, follow appropriate False
path
Single Selection (if)
If grade >=60
print passed
Double Selection (if-else)
– If grade >=60 : False True
Grade>=60
passed Failed ? passed
else:
failed
Selection (continued)
• Multiple Selection (switch) Light True
Stop
If the light is ... Red?

False
red -> stop True
Light
green -> go Green?
False
Go

True
yellow -> slow down Light Slow
Yellow? Down
False
Repetition

Teaching a baby to count


Counter = 1
from 1 to 10:
counter = 1
Add 1
to counter if counter <= 10:
increment counter
CounterTrue
Print print counter number
≤ 10?
counter
False
Examples
Example 4
Exercise

1. Draw a flowchart to match the following pseudocode.


- Give variable num1 a starting value of 5
- Give variable num2 a starting value of 10
- Add 7 to num2
- Store the value num1 times num2 in variable
num3
- Store the value num2 minus num1 in num2
- Output num1, num2 and num3
2. Trace the steps in your flowchart from question 1 and show
the output produced by this program.
5. Mechanics of Creating a
program (C++ IDE)
5.1 Introduction to C++
• Where did C++ come from?
– Derived from the C language
– C was derived from the B language
– B was derived from the BCPL language
5.2 C++ History
• C developed by Dennis Ritchie at AT&T
Bell Labs in the 1970s.
– Used to maintain UNIX systems
– Many commercial applications written in c
• C++ developed by Bjarne Stroustrup at AT&T
Bell Labs in the 1980s.
– Overcame several shortcomings of C
– Incorporated object oriented programming
– C remains a subset of C++
5.3 Mechanics of Creating a
program (C++ IDE)
• C++ programs typically go through five
phases to be executed: these are
– edit,
– preprocess,
– compile,
– link,
– load:
---Edit:
• this is accomplished with an editor program.
• The programmer types C++ statements with the
editor and makes corrections if necessary
• The programs source file is then stored on
secondary storage device such as a disk with a
“.cpp” file name.
• After the program is edited, C++ is principally
compiled in three phases: preprocessing,
translation to object code, and linking
• the last two phases are what is generally thought
of as the "compilation" process).
---Preprocess:
• In a C++ system, a preprocessor program executes
automatically before the compiler’s translation phase
begins.
• The C++ preprocessor obeys command called
preprocessor directives, which indicate that certain
manipulations are to be performed on the program
before compilation.
• The preprocessor is invoked by the compiler before the
program is converted to machine language.
• The C++ preprocessor goes over the program text and
carries out the instructions specified by the preprocessor
directives (e.g., #include). The result is a modified
program text which no longer contains any directives.
---Compile:
• Then, the C++ compiler translates the program code.
• The compiler converts source code to object code
• The compiler may be a true C++ compiler which
generates native (assembly or machine) code.
• The outcome may be incomplete due to the program
referring to library routines which are not defined as a
part of the program.
• For example, the << operator which is actually defined
in a separate IO library.
• This file is often named with the extension .OBJ
---Linking:
• C++ programs typically contain references to
functions and data defined else where, such as in the
standard libraries.
• The object code produced by the C++ compiler
typically contains “holes” due to these missing parts.
• A linker links the object code with the code for the
missing function to produce an executable image (with
no missing pieces).
• Generally, the linker completes the object code by
linking it with the object code of any library modules
that the program may have referred to.
• The final result is an executable file
---Loading:
• the loader takes the executable file from disk and
transfers it to memory.
• Additional components from shared libraries that
support the program are also loaded.
• Finally, the computer, under the control of its CPU,
executes the program.
• In practice all these steps are usually invoked by a
single command and the user will not even see the
intermediate files generated.
---From a High-Level Program to an
Executable File
Thank You

You might also like