0% found this document useful (0 votes)
14 views

Lecture 1 2

Uploaded by

amrfawzy951
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lecture 1 2

Uploaded by

amrfawzy951
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

MENOUFIA UNIVERSITY

FACULTY OF COMPUTERS AND INFORMATION


‫جامعة المنوفية‬

First Year (First Semester)


CS Dept., (CS131)

PRINCIPLES OF PROGRAMMING

LECTURE ONE & TWO

Dr. Hamdy M. Mousa


Today Proverb
‫فقط كن واثق في قدرة هللا ولن تندم ابدا‬
Be confident in the power of ALLAH and you will never regret
Computers and Programming
Computers & Programming
• In this lecture, you will learn about:
– Computer systems
– Simple program logic
– The steps involved in the program
development cycle
– Pseudocode statements and flowchart symbols
– Using a sentinel value to end a program
– Programming and user environments
– The evolution of programming models
Computers & Programming
• In this lecture, you will learn about:
– Declaring and Using Variables
– Arithmetic Operations
– Routine Components in Programs
• LOOPS, lf-Then-Else,
• Counter, Accumulator, Indicators
– Program Design
– Programming and user environments
– C++ Program

‫اعلم دائما ان غدا افضل‬


Always know that tomorrow is better
Computers & Programming
• Every computer system is composed of multiple
pieces of hardware and software.
• Hardware is the equipment, or the physical
devices.
– For example, keyboards, mice, speakers,
• Software is computer instructions that tell the
hardware what to do.
– Software is programs, which are instruction sets written
by programmers.
• For example, businesses use word-processing and accounting
programs and games.
• you can write your own programs.
Computers

“The Box”
CRT Display CD-ROM Drive

Floppy
Disk
Drive
Keyboard

Mouse
SOFTWARE TYPES
• System Software
– Operating systems
– Communications
– Device drivers and utilities
– Performance management
• Business Software
– General business
– Applications by business/interest area
– Desktop publishing
– Project management
– Image processing
• Development Software
– Programming languages
– Computer-assisted software engineering
– Web site development software
PROGRAMMING MODELS
• programmers to develop programs and
their procedures:
– Procedural programming focuses on the
procedures that programmers create.
• procedural programmers focus on the actions that
are carried.
– Object-oriented programming focuses on
objects, or “things,” and describes their
features (also called attributes) and
behaviors.
PROGRAMMING LANGUAGE
• You write computer instructions in a computer
programming language such as Visual Basic, C++, C#,
or Java.
• Programmers write programs in different languages.
– Some programmers work exclusively in one language,
• others know several and use the one that is best suited to the
task at hand.
• The instructions you write using a programming language
are called program code.
• Every programming language has rules governing its
word usage and punctuation.
– These rules are called the language’s syntax.
– Mistakes in a language’s usage are syntax errors.
COMPUTER LANGUAGES
• Computer languages may be divided into
three general types:
B i n a r y
– Machine languages
– Assembly languages
– High-level languages

• The process of compiling a high-level language program


into machine language can take a considerable amount
of computer time.
• Interpreter programs were developed to execute high-
level language programs directly, although much more
slowly.
UNDERSTANDING PROGRAMMING PROCESS

Programming steps:
1. Understand the problem.
2. Plan the logic.
3. Code the program.
4. Translate the program into machine
language.
5. Test the program.
6. Put the program into production.
7. Maintain the program.
1. Understanding the Problem

• Programmer
– Write programs to satisfy others needs
– Provide services to users
• First understand what users want
• Well designed program
– Steps might involve a short meeting
• Poorly designed program
– Steps might take many meeting hours
• Thoroughly understanding problem
– A most difficult aspect of programming
Envisioning the Objects

• Programmer
– Envisions objects needed
– Writes programming language instructions to
create objects
• Distinct steps
– Data modeling
• Identify all manipulated objects and relations
– Create class
• General object category
– Establish communication means
• Between objects, user
2. Planning the Logic

• Heart of programming process


• Programmer
– Plans program steps
– Decides steps to include and order
• Leads from available input to desired output
– Plans the solution: logic tools
• Flowcharts and pseudocode
• Both use English-like code
– Language syntax not a concern
3. Coding the Program

• Write class definitions


– Descriptions data in each class
– Operations performed with data in each class
• Object-oriented languages
– C++, C#, Java, Visual Basic, COBOL
– Similarity
• All create objects and establishing communication
3. Coding the Program (cont’d.)

• Program object and logic needed to work


with the objects
– Executed using any number of languages
• Syntax (correct spelling and punctuation )
– Concern once language chosen

• Experienced programmers
– Combine planning and program coding in
one step
4. Translating the Program Code

• Many programming languages


• Computer knows one language
– Its machine language consisting of many 1s and 0s
• Translator programs (compilers or interpreters)
– Change English-like high-level programming into low-
level machine language
• Executable program
• Syntax error
– Issues when translator cannot translate the code
– Must be corrected to allow compilation to complete
• Debugging is the process of finding and
correcting program errors.
5. Testing the Program

• Syntax error free program


– Not necessarily free of logical errors
– Must test for logical errors
• Requires entering of sample data
– Select test data carefully
– Error discovery may require changes
• To program logic
• To actual object design
• Process resembles syntax error correction cycle
6. Putting the Program into Production

• Program adequately tested


– Ready for organizational use
• Putting program into production
– Time to implement
• Can be short or long
• Depends on program nature, size and user needs
– Factors
• Training, data format changes, new platform causing
users to make choices in unanticipated
combinations
7. Maintaining the Program

• Maintenance
– Process of making required changes
• Reasons
– New legislated
– Input file format alterations
– End user requires additional information
• Not included in original output specifications
The program development cycle
Algorithm
• An algorithm is a set of rules or instructions for
doing a task or solving a problem.

• A computer program is simply an algorithm for


a computer that is written in a programming
language.

• The programmers often use one of two tools:


• pseudocode (pronounced sue-doe-code) or
• flowcharts
– to plan the logic for programming problem
solution.
Some symbols used in flowcharts

1- Terminal symbol
indicates the beginning and the end of processing.
Some symbols used in flowcharts

2- I/O symbol
indicates that the computer is to obtain new
data or to record the results of computations.

parallelogram
Some symbols used in flowcharts

3- Decision symbol
represents a branch in the flow of a program

diamond
Some symbols used in flowcharts
4- Process symbol
contains instructions that are not represented
by other symbols. i.e. it contains calculations,
storage of data.

rectangle
Some symbols used in flowcharts

5- Flow direction lines


indicate the flow of the program.
Arrowheads are drawn where flow direction lines join and
where flow direction lines meet other symbols.
Some symbols used in flowcharts

6- comment or annotation
symbol is used to annotate other entries.
dashed line indicates the position of the
comment.
Some symbols used in flowcharts

7- connector
is used to join areas of a flowchart.
Some symbols used in flowcharts

8- Striped symbol
is used to represent a predefined process (or series of
operations) when the flowcharts that define the process
are included with the current set of flowcharts.
Some symbols used in flowcharts

9- Predefined process symbol


is used to represent a predefined process when
the flowcharts that define the process are not
included with the current set of flowcharts.
Some Symbols Used in Flowcharts

10- Off-page connector


is used to join areas of a flowchart when the points
joined occur on different pages.
PSEUDOCODE
Pseudocode: (pronounced sue-doe-code) is
– an English-like representation
– used by programmers to plan the logical steps
for solving a programming problem.

• Pseudo is a prefix that means FALSE, and to


code a program means to put it in a programming
language, pseudocode simply means false code
• Pseudocode for a particular program is often
similar in appearance to the final coded program.
• The chief difference is that pseudocode does not
follow syntax rules of a programming language.
Example
Example

Start
Read InputNumber
Result = InputNumber * 2
Print Result
Stop
Figure shows symbols and the flow direction lines
Repeating Instructions
start
input myNumber
set myAnswer = myNumber * 2
output myAnswer
input myNumber
set myAnswer = myNumber * 2
output myAnswer
input myNumber
set myAnswer = myNumber * 2
output myAnswer
….
…..
…..
Stop
Repeating Instructions

infinite loop
Using a Sentinel Value to End a Program
Complex Flowchart
Figure shows the Flowchart for what will happen to the values of X and Y
as the program runs

X Y
1 1
2 2
1 3
2 4
1
2
Figure shows the Flowchart for what will happen to the values of
X and Y as the program runs

X Y Y
1 1
2 2 2
2 3 3
1 3
2 3
2 4 4
Exercises
Exercises: 1 Examine the following flowchart, fill in the table of values, and
answer the questions.
a. What numbers will be printed?
b. What values will X and Y have when the program ends?
Exercises
Exercises: 2- Examine the following flowchart, and fill in the table values.
What will the values of X, Y, and Z be when this program ends?
Computers, Memory, and
Input/Output
Computers can be viewed as consisting of three
types of components: input devices; output
devices; and the central processing unit, or
CPU.
Declaring and Using Variables
• All programming languages support two broad
data types;
– numeric describes data that consists of numbers
– string describes data that is nonnumeric.
• numeric constant is specific numeric value,
– such as 43, 12345800 within a program.
• string constant (literal string constant) is A specific text
value, or string of characters,
– such as “Amanda” , “ 1000$”
• Variables are named memory locations whose contents can vary
or differ over time.
Variables
Declaration
• In most programming languages, before
you can use any variable, you must
include a declaration for it.
– A declaration is a statement that provides a
data type and an identifier for a variable.

• An identifier is a program component’s


name.
Variables
Declaration
• Optionally, initializing the variable
– For example,
• num mySalary
• num yourSalary = 14.55
• string myName
• string yourName = “Ahmed“

• if you declare a variable and do not initialize it,


the variable contains an unknown value until it
is assigned a value.
– A variable’s unknown value commonly is called garbage.
Variable Names
• Different languages put different limits on the length of
variable names,
– in general, the length of identifiers in newer languages is
virtually unlimited.
• Some rules of variable names:
– Variable names must be one word. The name can contain
letters, digits, hyphens, underscores, or any other
characters you choose, with the exception of spaces. i.e.
• r, rate and interestRate is a legal variable name, as are.
• interest rate is not allowed because of the space.
– Variable names must start with a letter. Some programming
languages allow variable names to start with a non-alphabetic
character such as an underscore.
– It is preferred, Variable names should have some appropriate
meaning.
Assigning Values to Variables
Computer Memory
It is convenient to picture a
computer's memory as
consisting of a large number of
locations in which data can be
stored

Example:
instruction NUMBER = 2
directs the computer to store the value 2 at the location
that it is calling NUMBER.
NUMBER 2 46.38 10.00
=2 NUMBER COST PROFIT
INSTRUCTION COMPUTER STORAGE
Assigning Values to Variables

Instruction ADD 1 TO NUMBER

ADD 1 TO 2 3 46.38 10.00


NUMBER NUMBER COST PROFIT
INSTRUCTION COMPUTER STORAGE

Instruction NUMBER = COST

NUMBER = 3 46.38 46.38 10.00


COST NUMBER COST PROFIT
INSTRUCTION COMPUTER STORAGE
Assigning Values to Variables

Instruction NUMBER = COST + PROFIT

NUMBER = 56.38 46.38 10.00


COST
+ PROFIT NUMBER COST PROFIT
INSTRUCTION COMPUTER STORAGE

If we want to store the word yes at a location that we


were calling FLAG, we would use the instruction FLAG
= "YES".

FLAG = "YES" YES


INSTRUCTION FLAG
Assigning Values to Variables

Figure describes a portion of a computer's


memory before and after a series of
instructions is executed.
Assume that data in the "before" table
resulted from previous instructions.
Input/Output
Most computer operations require data to be entered
and results to be printed, displayed, or recorded.
CUSTOMER FILE
JOE SMITH 621 MAIN 47 CUSTOMER RECORD
TOM ADAMS 418 SOUTH 26
MARK BARNS 149 CREST 44
MARY THOMAS 31 6 EAST 37
FRED JONES 947 ADA 52
… … ...
/* EOF MARKER
NAME ADDRESS AGE
FIELD FIELD FIELD

A single input instruction (READ) obtains all the


appropriate data from a single record.
Input/Output
Instruction READ NAME, ADDRESS, AGE
directs the computer to store data from three fields of the
next record at three memory locations called NAME,
ADDRESS, and AGE

Note:
Once data is stored in memory, it remains until the
instruction to read is executed again.
Place the EOF decision AFTER the corresponding READ.
Tests for EOF BEFORE executing the READ instruction.
PRINT
- To print a line on a report, we will use the instruction
PRINT.
- The PRINT instruction directs the computer to print information
stored at one or more of its memory locations.
PRINT
In addition to data stored in memory, PRINT instructions
may be used to print literals.

Instruction Line Printed

PRINT NAME JOE SMITH


PRINT "NAME" NAME
PRINT "NAME", NAME NAME JOE SMITH
PRINT "NAME", NAME, "AGE", AGE NAME JOE SMITH AGE 47
PRINT "MY NAME IS", NAME MY NAME IS JOE SMITH
PRINT NAME, "IS", AGE, "." JOE SMITH IS 47.
Figure describes a program that will read records from
the customer file and print a report containing the
information from each record.
OPEN & CLOSE Files
Note:
Files must be opened and closed.

Because OPEN and CLOSE instructions are


not universally required—and especially
because they pose no interesting problems
in the logic of program design
PSEUDOCODE
Write pseudocode to:
- read name and gross pay from each record.
- print the name and fed W/H
If Gross Pay > 400 >>> Fed W/H = Gross Pay X 25%
Else
Fed W/H = Gross Pay X 17%

START
READ NAME, GROSS PAY
DO CALCULATE FED W/H LOOP WHILE NOT EOF
IF GROSS PAY > 400
FED W/H = GROSS PAY X 25 %
ELSE
FED W/H = GROSS PAY X 17 %
END IF
PRINT NAME, FED W/H
READ NAME, GROSS PAY
END DO
STOP
Performing Arithmetic Operations
Precedence and associativity of five common operators

Operator Operator Precedence


Associativity
symbol name (compared to other operators)

= Assignment Right-to-left Lowest


+ Addition Left-to-right Medium
- Subtraction Left-to-right Medium
* Multiplication Left-to-right Highest
/ Division Left-to-right Highest

Example:
answer = a + b + c * d / e – f
answer = 7 + 18/6 - 2 * 5
answer = a + b + ((c * d) / e) – f
Sequence
A sequence is represented by listing a
series of instructions at the same margin

STOTAL = 0
GTOTAL = 0
READ NAME, SALES
Routine Components in Programs

I. Loop
Loop is a circular logical structure.
It causes a series of steps to be continuously
repeated until a decision directs program flow to
some other part of the program.
Loops are diagrammed in either of two ways:
1. By an upward flow direction line.
2. By a connector that returns program flow to a
previous point on the chart.
I. Loop
LOOPS
Loops are represented by statements that indicate
the name of the loop, the type of loop (while or
until), and the loop exit decision.

DO COUNT LOOP WHILE NOT (COUNT > 10)


READ AMOUNT
ADD AMOUNT TO TOTAL
ADD 1 TO COUNT
END DO
EXAMPLE of single loop containing a variety of symbols

Start
Read Name, Gross Pay
DO Calc LOOP WHILE NOT EOF
Read Name, Gross Pay
Fed Tax= Gross Pay X 17%
SS Tax= Gross Pay X 6%
Print Name, Fed Tax, SS Tax
END DO
Nested loops
LOOPS

DO COUNT LOOP UNTIL COUNT > 10


READ AMOUNT
ADD AMOUNT TO TOTAL
ADD 1 TO COUNT
END DO
lf-Then-Else
lf-Then
IF

IF COMMISSION > 0
ADD COMMISSION TO TOTAL
ADD BONUS TO TOTAL
END IF
lf-Then-Else

IF SALES > 0
SKIP
ELSE
PRINT "ERROR IN DATA"
ADD 1 TO ERROR RECORDS
END IF
Nested If-Then-Elses
Routine Components in Programs
II. COUNTER
count of the number of times a
process within a loop has been
completed.
A counter consists of two processes that
manipulate a variable:
- initializes the variable
- The second adds/subtract a constant to
(or increments/decrement) the variable
each time the loop is completed.
Example of flowchart contains a counter
The flowchart illustrates the error of initializing the
variable within the loop itself.
The flowchart prints a report of records in a file called
"SALES FILE."
Routine Components in Programs

III. An accumulator
It is a structure that maintains a current total
without affecting ongoing calculations or
processing.
- Accumulators are similar to counters in that
both consist of a process that sets a variable
equal to an initial value and another process
that, increments that variable.
- Accumulators differ from counters in that they
are incremented by variable amounts rather than
by constants.
The flowchart represents a simple program that contains an
accumulator called TOTAL. In this flowchart, the profit for each
item is accumulated in TOTAL. When EOF is reached, this total is
printed.
Flowchart (uses both a counter and an accumulator)
represents a program that will read a series of sales and
calculate and print their average.
Routine Components in Programs
IV. indicators (Switches or Flags)
Indicators, often called switches or flags, are
used to record some event or circumstance
within a program.

An indicator consists of two elements:


- A process that initializes a variable (sets that
variable at a predetermined value).
- A process that stores a different predetermined
value as the value of that variable when the
particular event occurs.
A message would be printed at the end of the program to indicate
whether or not any of the profits exceeded 1500.
Universal Requirements for Flowcharts

Every flowchart must


1. Start somewhere.
2. Stop somewhere.
3. Unfailingly reach the stop.
This flowchart illustrates two common errors in flowcharting.
This flowchart contains an endless loop
that results from its content

You might also like