SlideShare a Scribd company logo
1 of 55
ALGORITHMS AND FLOWCHARTS
ALGORITHMS AND FLOWCHARTS

• A typical programming task can be divided into two
  phases:
• Problem solving phase
   – produce an ordered sequence of steps that describe
     solution of problem
   – this sequence of steps is called an algorithm
• Implementation phase
   – implement the program in some programming language
Steps in Problem Solving
• First produce a general algorithm (one can use
  pseudocode)
• Refine the algorithm successively to get step by step
  detailed algorithm that is very close to a computer
  language.
• Pseudocode is an artificial and informal language
  that helps programmers develop algorithms.
  Pseudocode is very similar to everyday English.
Pseudocode & Algorithm
• Example 1: Write an algorithm to determine a
  student’s final grade and indicate whether it is
  passing or failing. The final grade is calculated
  as the average of four marks.
Pseudocode & Algorithm
Pseudocode:
• Input a set of 4 marks
• Calculate their average by summing and dividing by 4
• if average is below 50
       Print “FAIL”
  else
       Print “PASS”
Pseudocode & Algorithm
• Detailed Algorithm
•    Step 1:       Input M1,M2,M3,M4
     Step 2:       GRADE (M1+M2+M3+M4)/4
     Step 3:       if (GRADE < 50) then
                          Print “FAIL”
                   else
                          Print “PASS”
                   endif
The Flowchart
A Flowchart
  – shows logic of an algorithm
  – emphasizes individual steps and their
    interconnections
  – e.g. control flow from one action to the next
Flowchart Symbols
                         Basic
Name            Symbol       Use in Flowchart


Oval                             Denotes the beginning or end of the program




Parallelogram                    Denotes an input operation




Rectangle                    Denotes a process to be carried out
                             e.g. addition, subtraction, division etc.




Diamond                      Denotes a decision (or branch) to be made.
                             The program should continue along one of
                             two routes. (e.g. IF/THEN/ELSE)




Hybrid                           Denotes an output operation




Flow line                        Denotes the direction of logic flow in the program
Example
                 START
                                       Step 1:   Input M1,M2,M3,M4
                                       Step 2:   GRADE (M1+M2+M3+M4)/4
                Input
             M1,M2,M3,M4
                                       Step 3:   if (GRADE <50) then
                                                          Print “FAIL”
                                                 else
    GRADE   (M1+M2+M3+M4)/4                               Print “PASS”
                                                 endif
    N            IS           Y
              GRADE<50



PRINT                         PRINT
“PASS”                        “FAIL”




                STOP
Example 2
• Write an algorithm and draw a flowchart to
  convert the length in feet to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by
  multiplying LFT with 30
• Print length in cm (LCM)
Example 2
Algorithm                 Flowchart

• Step 1: Input Lft         START


• Step 2: Lcm Lft x 30          Input
                                  Lft

• Step 3: Print Lcm
                          Lcm      Lft x 30



                                Print
                                Lcm




                                STOP
Example 3
  Write an algorithm and draw a flowchart that will
  read the two sides of a rectangle and calculate its
  area.
Pseudocode
• Input the width (W) and Length (L) of a rectangle
• Calculate the area (A) by multiplying L with W
• Print A
Example 3

Algorithm                     START


• Step 1: Input W,L           Input
                               W, L
• Step 2: A L x W
• Step 3: Print A         A     LxW



                              Print
                               A




                              STOP
Example 4
• Write an algorithm and draw a flowchart that will
  calculate the roots of a quadratic equation
   ax 2 bx c 0


• X=(-b + sqrt (b2 -4ac))/2a
• X=(-b - sqrt (b2 -4ac))/2a
Example 4
Pseudocode:
• Input the coefficients (a, b, c) of the quadratic
  equation
• Calculate d
• Calculate x1
• Calculate x2
• Print x1 and x2
Example 4
                                                START

• Algorithm:
                                                    Input
•   Step 1:   Input a, b, c                         a, b, c
•   Step 2:   d sqrt ( b b 4 a ) c
•   Step 3:   x1 (–b + d) / (2 x a)   d        sqrt(b x b – 4 x a x c)

•   Step 4:   x2 (–b – d) / (2 x a)
                                          x1     (–b + d) / (2 x a)
•   Step 5:   Print x1, x2
                                          X2     (–b – d) / (2 x a)

                                                    Print
                                                    x1 ,x2



                                                    STOP
DECISION STRUCTURES
• The expression A>B is a logical expression
• it describes a condition we want to test
• if A>B is true (if A is greater than B) we take the
  action on left
• print the value of A
• if A>B is false (if A is not greater than B) we take the
  action on right
• print the value of B
DECISION STRUCTURES



       Y            N
             is
            A>B


  Print A         Print B
IF–THEN–ELSE STRUCTURE
• The structure is as follows
If condition then
       true alternative
   else
       false alternative
endif
IF–THEN–ELSE STRUCTURE
• The algorithm for the flowchart is as follows:
If A>B then
   print A
else                     Y
                               is
                                         N

   print B                    A>B

endif
                      Print A          Print B
Relational Operators

           Relational Operators
Operator                     Description
   >          Greater than
   <          Less than
   =          Equal to
              Greater than or equal to
              Less than or equal to
              Not equal to
Example 5
• Write an algorithm that reads two values, determines the
   largest value and prints the largest value with an identifying
   message.
ALGORITHM
Step 1:         Input VALUE1, VALUE2
Step 2:         if (VALUE1 > VALUE2) then
                        MAX VALUE1
                else
                        MAX VALUE2
                endif
Step 3:         Print “The largest value is”, MAX
Example 5
                   START



                    Input
                VALUE1,VALUE2



        Y               is
                                        N
                  VALUE1>VALUE2




MAX   VALUE1                      MAX       VALUE2




                    Print
         “The largest value is”, MAX



                    STOP
NESTED IFS
• One of the alternatives within an IF–THEN–
  ELSE statement
  – may involve further IF–THEN–ELSE statement
Example 6
• Write an algorithm that reads three numbers
  and prints the value of the largest number.
Example 6
Step 1: Input       N1, N2, N3
Step 2: if (N1>N2) then
              if (N1>N3) then
                    MAX N1         [N1>N2, N1>N3]
             else
                    MAX N3         [N3>N1>N2]
            endif
         else
             if (N2>N3) then
                    MAX N2         [N2>N1, N2>N3]
            else
                    MAX N3         [N3>N2>N1]
            endif
         endif
Step 3: Print “The largest number is”, MAX
Example 6
• Flowchart: Draw the flowchart of the above
  Algorithm.
Example 7

• Write and algorithm and draw a flowchart to
a) read an employee name (NAME), overtime
   hours worked (OVERTIME), hours absent
   (ABSENT) and
b) determine the bonus payment (PAYMENT).
Example 7
               Bonus Schedule
OVERTIME – (2/3)*ABSENT   Bonus Paid


>40 hours                 $50
>30 but 40 hours          $40
>20 but 30 hours          $30
>10 but 20 hours          $20
  10 hours                $10
Step 1: Input NAME,OVERTIME,ABSENT
Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then
           PAYMENT 50
         else if (OVERTIME–(2/3)*ABSENT > 30) then
             PAYMENT 40
         else if (OVERTIME–(2/3)*ABSENT > 20) then
             PAYMENT 30
         else if (OVERTIME–(2/3)*ABSENT > 10) then
             PAYMENT 20
         else
             PAYMENT 10
         endif
Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
Example 7
• Flowchart: Draw the flowchart of the above
  algorithm?
Objectives
• In this chapter you will be able to:

• Introduce common words, keywords, and meaningful
  names when writing pseudocode

• Define the three basic control structures as set out in the
  Structure Theorem

• Illustrate the three basic control structures using
  pseudocode


                      Simple Program Design, Fourth Edition
                                                              32
                                   Chapter 2
How to Write Pseudocode
• When designing a solution algorithm, you need
  to keep in mind that a computer will eventually
  perform the set of instructions written

• If you use words and phrases in the pseudocode
  which are in line with basic computer operations,
  the translation from pseudocode algorithm to a
  specific programming language becomes quite
  simple

                  Simple Program Design, Fourth Edition
                                                          33
                               Chapter 2
Six Basic Computer Operations
1 A computer can receive information
  – When a computer is required to receive
    information or input from a particular source,
    whether it is a terminal, a disk or any other
    device, the verbs Read and Get are used in
    pseudocode                     Example pseudocode

                                                   Read student name
                                                   Get system data
  Read => Input from a record                      Read number1, number2
                                                   Get tax_code
  Get => Input from keyboard
                   Simple Program Design, Fourth Edition
                                                                           34
                                Chapter 2
Six Basic Computer Operations
1 A computer can receive information
  – Usually an output Prompt instruction is required
    before an input Get instruction


            Example pseudocode

            Prompt for student_mark
            Get student_mark




                    Simple Program Design, Fourth Edition
                                                            35
                                 Chapter 2
Six Basic Computer Operations
2 A computer can put out information
  – When a computer is required to supply
    information or output to a device, the verbs Print,
    Write, Put, Output, or Display are used in
    pseudocode                          Example pseudocode
                                        Print ‘Program Completed’
  – Print => send output to printer     Write customer record to master
                                        Output total tax
  – Write => send out to file           Display ‘End of data’

  – Put, Output, Display => send to screen


                     Simple Program Design, Fourth Edition
                                                                36
                                  Chapter 2
Six Basic Computer Operations
3   A computer can perform arithmetic
    –   Most programs require the computer to perform some sort of mathematical
        calculation, or formula, and for these, a programmer may use either actual
        mathematical symbols or the words for those symbols
    –   To be consistent with high-level programming languages, the following
        symbols can be written in pseudocode:
        + for Add          - for Subtract
        * for Multiply                 / for Divide                 ( ) for Parentheses
    –   When writing mathematical calculations for the computer, standard
        mathematical ‘order of operations’ applies to pseudocode and most
        computer languages




                            Simple Program Design, Fourth Edition
                                                                                          37
                                         Chapter 2
Six Basic Computer Operations
4 A computer can assign a value to a variable or
  memory location
  – There are three cases where you may write
    pseudocode to assign a value to a variable or
    memory location:
     1. To give data an initial value in pseudocode, the verbs
        Initialize or Set are used
     2. To assign a value as a result of some processing the symbols
        ‘=‘ or ‘ ’ are written
     3. To keep a variable for later use, the verbs Save or Store are
        used

                      Simple Program Design, Fourth Edition
                                                                        38
                                   Chapter 2
Six Basic Computer Operations
4 A computer can assign a value to a variable or
  memory location

      Example pseudocode

      Initialize total_price to zero
      Set student_count to zero
      Total_price = cost_price + sales_tax
      Total_price  cost_price + sales_tax
      Store customer_num in last_customer_num




                      Simple Program Design, Fourth Edition
                                                              39
                                   Chapter 2
Six Basic Computer Operations
5 A computer can compare two variables and
  select one or two alternate actions

  – An important computer operation available to the
    programmer is the ability to compare two variables
    and then, as a result of the comparison, select one of
    two alternate actions

  – To represent this operation in pseudocode, special
    keywords are used: IF, THEN, and ELSE

                   Simple Program Design, Fourth Edition
                                                           40
                                Chapter 2
Six Basic Computer Operations
6 A computer can repeat a group of actions

   – When there is a sequence of processing steps that need to be
      repeated, two special keywords, DOWHILE and ENDDO, are
      used in pseudocode

   – The condition for the repetition of a group of actions is
      established in the DOWHILE clause, and the actions to be
      repeated are listed beneath it



                        Simple Program Design, Fourth Edition
                                                                    41
                                     Chapter 2
Meaningful Names
• All names should be meaningful
• A name given to a variable is simply a method of identifying a particular
  storage location in the computer
• The uniqueness of a name will differentiate it from other locations
• Often a name describes the type of data stored in a particular variable
• Most programming languages do not tolerate a space in a variable name,
  as a space would signal the end of the variable name and thus imply that
  there were two variables




                           Simple Program Design, Fourth Edition
                                                                              42
                                        Chapter 2
The Structure Theorem
• The Structure Theorem states that it is possible to
  write any computer program by using only three
  basic control structures that are easily represented in
  pseudocode:
   – Sequence
   – Selection
   – Repetition




                    Simple Program Design, Fourth Edition
                                                            43
                                 Chapter 2
The Three Basic Control Structures
1   Sequence
    –   The sequence control structure is the straightforward execution of one
        processing step after another
    –   In pseudocode, we represent this construct as a sequence of pseudocode
        statements
2   Selection
    –   The selection control structure is the presentation of a condition and the
        choice between two actions; the choice depends on whether the condition is
        true or false
    –   In pseudocode, selection is represented by the keywords IF, THEN, ELSE, and
        ENDIF




                            Simple Program Design, Fourth Edition
                                                                                 44
                                         Chapter 2
The Three Basic Control Structures
3 Repetition

  – The repetition control structure can be defined as the
    presentation of a set of instructions to be performed
    repeatedly, as long as a condition is true

  – The basic idea of repetitive code is that a block of
    statements is executed again and again, until a
    terminating condition occurs

  – This construct represents the sixth basic computer
    operation, namely to repeat a group of actions

                    Simple Program Design, Fourth Edition
                                                            45
                                 Chapter 2
Summary
• In this chapter, six basic computer operations were listed, along
  with pseudocode words and keywords to represent them
• These operations were: to receive information, put out information,
  perform arithmetic, assign a value to a variable, decide between
  two alternate actions, and repeat a group of actions
• The Structure Theorem was introduced; it states that it is possible
  to write any computer program by using only three basic control
  structures: sequence, selection, and repetition




                         Simple Program Design, Fourth Edition
                                                                        46
                                      Chapter 2
Someone Stole a Cookie from the Cookie Jar

Problem: Momma had just filled the cookie jar
  when the 3 children went to bed. That night
  one child woke up, ate half of the cookies
  and went back to bed. Later, the second
  child woke up, ate half of the remaining
  cookies, and went back to bed. Still later,
  the third child woke up, ate half of the
  remaining cookies, leaving 3 cookies in the
  jar. How many cookies were in the jar to
  begin with?
Someone Stole a Cookie from the Cookie Jar (cont’d)


• Information available:
   – Three children
   – Each one ate half of the cookies
   – Three cookies remaining
• Information needed:
   – Original number of cookies
• Calculations:
   – For each child, multiply the number of remaining cookies
     by two.
Specific Solution to the Problem
• First, we solve the specific problem to help us
  identify the steps.
  – 3 cookies left X 2 = 6 cookies left after
                    2nd child
  – 6 X 2 = 12 cookies left after 1st child
  – 12 X 2 = 24 = original number of cookies
A Generic Algorithm
• What is a generic algorithm for this problem?

    An algorithm that will work with any number of
    remaining cookies
                       AND
    that will work with any number of children.
Generic Algorithm for Cookie Problem

• Get number of children.
• Get number of cookies remaining.
• While there are still children that have not
  raided the cookie jar, multiply the number
  of cookies by 2 and reduce the number of
  children by 1.
• Display the original number of cookies.
Test The Generic Algorithm
• Try the algorithm on paper with:
  – Four children and six cookies remaining.
  – Two children with two cookies remaining.
• If you did not get the correct answer, modify
  the algorithm so that you get the correct
  answer.
Pseudocode
• When we broke down the previous problem
  into steps, we expressed each step as an English
  phrase.
• We can think of this as writing pseudocode for
  the problem.
• Typically, pseudocode is a combination of
  English phrases and formulas.
Pseudocode (con’t)
• Pseudocode is used in
  – designing algorithms
  – communicating an algorithm to the customer
  – converting an algorithm to code (used by the
    programmer)
  – debugging logic (semantic) errors in a solution
    before coding (hand tracing)
• Let’s write the Cookie Problem algorithm using
  a more formal pseudocode and being more
  precise.
Improved Pseudocode
Display “Enter the number of children: “
Read <number of children>
Display “Enter the number of cookies remaining: “
Read <cookies remaining>
<original cookies> = <cookies remaining>
While (<number of children> > 0)
    <original cookies> = <original cookies> X 2
    <number of children> = <number of children> - 1
End_While
Display “Original number of cookies = “, <original cookies>

More Related Content

What's hot

trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
6.applet programming in java
6.applet programming in java6.applet programming in java
6.applet programming in javaDeepak Sharma
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
 
Chapter 2 Representation Of Algorithms 2
Chapter 2  Representation Of  Algorithms 2Chapter 2  Representation Of  Algorithms 2
Chapter 2 Representation Of Algorithms 2Li-Anne Serrano
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++Ankur Pandey
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsOMWOMA JACKSON
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using BacktrackingAbhishek Singh
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
introduction to visual basic PPT.pptx
introduction to visual basic PPT.pptxintroduction to visual basic PPT.pptx
introduction to visual basic PPT.pptxclassall
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowchartsSamuel Igbanogu
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEdureka!
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchartRabin BK
 
TOC 2 | Deterministic Finite Automata
TOC 2 | Deterministic Finite AutomataTOC 2 | Deterministic Finite Automata
TOC 2 | Deterministic Finite AutomataMohammad Imam Hossain
 

What's hot (20)

C++ Problem solving
C++ Problem solvingC++ Problem solving
C++ Problem solving
 
What is c
What is cWhat is c
What is c
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
6.applet programming in java
6.applet programming in java6.applet programming in java
6.applet programming in java
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
Chapter 2 Representation Of Algorithms 2
Chapter 2  Representation Of  Algorithms 2Chapter 2  Representation Of  Algorithms 2
Chapter 2 Representation Of Algorithms 2
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
introduction to visual basic PPT.pptx
introduction to visual basic PPT.pptxintroduction to visual basic PPT.pptx
introduction to visual basic PPT.pptx
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
TOC 2 | Deterministic Finite Automata
TOC 2 | Deterministic Finite AutomataTOC 2 | Deterministic Finite Automata
TOC 2 | Deterministic Finite Automata
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 

Viewers also liked

Fundamental Programming Lect 5
Fundamental Programming Lect 5Fundamental Programming Lect 5
Fundamental Programming Lect 5Namrah Erum
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2Kumar
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Adam Mukharil Bachtiar
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsGanesh Solanke
 
Problem solving techniques
Problem solving techniquesProblem solving techniques
Problem solving techniquesAhsan Saleem
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 
Programming fundamentals lecture 1&2
Programming fundamentals lecture 1&2Programming fundamentals lecture 1&2
Programming fundamentals lecture 1&2Raja Hamid
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving TechniquesAshesh R
 
BASIC Programming Language
BASIC Programming LanguageBASIC Programming Language
BASIC Programming LanguageJeff Valerio
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1luhkahreth
 

Viewers also liked (12)

Fundamental Programming Lect 5
Fundamental Programming Lect 5Fundamental Programming Lect 5
Fundamental Programming Lect 5
 
Algorithmic Notations
Algorithmic NotationsAlgorithmic Notations
Algorithmic Notations
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
 
Big o
Big oBig o
Big o
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Problem solving techniques
Problem solving techniquesProblem solving techniques
Problem solving techniques
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Programming fundamentals lecture 1&2
Programming fundamentals lecture 1&2Programming fundamentals lecture 1&2
Programming fundamentals lecture 1&2
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
BASIC Programming Language
BASIC Programming LanguageBASIC Programming Language
BASIC Programming Language
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1
 

Similar to Programming fundamentals lecture 4

Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1Jesuraj Love
 
Algorithms and flowcharts1
Algorithms and flowcharts1Algorithms and flowcharts1
Algorithms and flowcharts1Lincoln School
 
1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowchartsDani Garnida
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1rajnidhiman
 
Programming fundamentals lecture 2 of c
Programming fundamentals lecture 2 of cProgramming fundamentals lecture 2 of c
Programming fundamentals lecture 2 of cRaja Hamid
 
01 Algorithms And Flowcharts.ppt
01 Algorithms And Flowcharts.ppt01 Algorithms And Flowcharts.ppt
01 Algorithms And Flowcharts.pptFerdieBalang
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and FlowchartsDeva Singh
 
Algorithms and flowcharts ppt (seminar presentation)..
 Algorithms and flowcharts  ppt (seminar presentation).. Algorithms and flowcharts  ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..Nagendra N
 
256958.ppt
256958.ppt256958.ppt
256958.pptBimlesh7
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowchartskhair20
 
ALGORITHMS AND FLOWCHARTS
ALGORITHMS AND FLOWCHARTSALGORITHMS AND FLOWCHARTS
ALGORITHMS AND FLOWCHARTSKate Campbell
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
algorithms and flow chart overview.pdf
algorithms and flow chart overview.pdfalgorithms and flow chart overview.pdf
algorithms and flow chart overview.pdfAmanPratik11
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesTech
 
Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm DevelopmentALI RAZA
 
programming fortran 77 Slide01
programming fortran 77 Slide01programming fortran 77 Slide01
programming fortran 77 Slide01Ahmed Gamal
 

Similar to Programming fundamentals lecture 4 (20)

Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1
 
Algorithms and flowcharts1
Algorithms and flowcharts1Algorithms and flowcharts1
Algorithms and flowcharts1
 
1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1
 
Programming fundamentals lecture 2 of c
Programming fundamentals lecture 2 of cProgramming fundamentals lecture 2 of c
Programming fundamentals lecture 2 of c
 
01 Algorithms And Flowcharts.ppt
01 Algorithms And Flowcharts.ppt01 Algorithms And Flowcharts.ppt
01 Algorithms And Flowcharts.ppt
 
Algorithmsandflowcharts1
Algorithmsandflowcharts1Algorithmsandflowcharts1
Algorithmsandflowcharts1
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and Flowcharts
 
Algorithms&flowcharts
Algorithms&flowchartsAlgorithms&flowcharts
Algorithms&flowcharts
 
Algorithms and flowcharts ppt (seminar presentation)..
 Algorithms and flowcharts  ppt (seminar presentation).. Algorithms and flowcharts  ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..
 
Algorithms&flowcharts
Algorithms&flowchartsAlgorithms&flowcharts
Algorithms&flowcharts
 
256958.ppt
256958.ppt256958.ppt
256958.ppt
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 
ALGORITHMS AND FLOWCHARTS
ALGORITHMS AND FLOWCHARTSALGORITHMS AND FLOWCHARTS
ALGORITHMS AND FLOWCHARTS
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
algorithms and flow chart overview.pdf
algorithms and flow chart overview.pdfalgorithms and flow chart overview.pdf
algorithms and flow chart overview.pdf
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing Techniques
 
Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm Development
 
programming fortran 77 Slide01
programming fortran 77 Slide01programming fortran 77 Slide01
programming fortran 77 Slide01
 

Programming fundamentals lecture 4

  • 2. ALGORITHMS AND FLOWCHARTS • A typical programming task can be divided into two phases: • Problem solving phase – produce an ordered sequence of steps that describe solution of problem – this sequence of steps is called an algorithm • Implementation phase – implement the program in some programming language
  • 3. Steps in Problem Solving • First produce a general algorithm (one can use pseudocode) • Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language. • Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is very similar to everyday English.
  • 4. Pseudocode & Algorithm • Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.
  • 5. Pseudocode & Algorithm Pseudocode: • Input a set of 4 marks • Calculate their average by summing and dividing by 4 • if average is below 50 Print “FAIL” else Print “PASS”
  • 6. Pseudocode & Algorithm • Detailed Algorithm • Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then Print “FAIL” else Print “PASS” endif
  • 7. The Flowchart A Flowchart – shows logic of an algorithm – emphasizes individual steps and their interconnections – e.g. control flow from one action to the next
  • 8. Flowchart Symbols Basic Name Symbol Use in Flowchart Oval Denotes the beginning or end of the program Parallelogram Denotes an input operation Rectangle Denotes a process to be carried out e.g. addition, subtraction, division etc. Diamond Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE) Hybrid Denotes an output operation Flow line Denotes the direction of logic flow in the program
  • 9. Example START Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Input M1,M2,M3,M4 Step 3: if (GRADE <50) then Print “FAIL” else GRADE (M1+M2+M3+M4)/4 Print “PASS” endif N IS Y GRADE<50 PRINT PRINT “PASS” “FAIL” STOP
  • 10. Example 2 • Write an algorithm and draw a flowchart to convert the length in feet to centimeter. Pseudocode: • Input the length in feet (Lft) • Calculate the length in cm (Lcm) by multiplying LFT with 30 • Print length in cm (LCM)
  • 11. Example 2 Algorithm Flowchart • Step 1: Input Lft START • Step 2: Lcm Lft x 30 Input Lft • Step 3: Print Lcm Lcm Lft x 30 Print Lcm STOP
  • 12. Example 3 Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area. Pseudocode • Input the width (W) and Length (L) of a rectangle • Calculate the area (A) by multiplying L with W • Print A
  • 13. Example 3 Algorithm START • Step 1: Input W,L Input W, L • Step 2: A L x W • Step 3: Print A A LxW Print A STOP
  • 14. Example 4 • Write an algorithm and draw a flowchart that will calculate the roots of a quadratic equation ax 2 bx c 0 • X=(-b + sqrt (b2 -4ac))/2a • X=(-b - sqrt (b2 -4ac))/2a
  • 15. Example 4 Pseudocode: • Input the coefficients (a, b, c) of the quadratic equation • Calculate d • Calculate x1 • Calculate x2 • Print x1 and x2
  • 16. Example 4 START • Algorithm: Input • Step 1: Input a, b, c a, b, c • Step 2: d sqrt ( b b 4 a ) c • Step 3: x1 (–b + d) / (2 x a) d sqrt(b x b – 4 x a x c) • Step 4: x2 (–b – d) / (2 x a) x1 (–b + d) / (2 x a) • Step 5: Print x1, x2 X2 (–b – d) / (2 x a) Print x1 ,x2 STOP
  • 17. DECISION STRUCTURES • The expression A>B is a logical expression • it describes a condition we want to test • if A>B is true (if A is greater than B) we take the action on left • print the value of A • if A>B is false (if A is not greater than B) we take the action on right • print the value of B
  • 18. DECISION STRUCTURES Y N is A>B Print A Print B
  • 19. IF–THEN–ELSE STRUCTURE • The structure is as follows If condition then true alternative else false alternative endif
  • 20. IF–THEN–ELSE STRUCTURE • The algorithm for the flowchart is as follows: If A>B then print A else Y is N print B A>B endif Print A Print B
  • 21. Relational Operators Relational Operators Operator Description > Greater than < Less than = Equal to Greater than or equal to Less than or equal to Not equal to
  • 22. Example 5 • Write an algorithm that reads two values, determines the largest value and prints the largest value with an identifying message. ALGORITHM Step 1: Input VALUE1, VALUE2 Step 2: if (VALUE1 > VALUE2) then MAX VALUE1 else MAX VALUE2 endif Step 3: Print “The largest value is”, MAX
  • 23. Example 5 START Input VALUE1,VALUE2 Y is N VALUE1>VALUE2 MAX VALUE1 MAX VALUE2 Print “The largest value is”, MAX STOP
  • 24. NESTED IFS • One of the alternatives within an IF–THEN– ELSE statement – may involve further IF–THEN–ELSE statement
  • 25. Example 6 • Write an algorithm that reads three numbers and prints the value of the largest number.
  • 26. Example 6 Step 1: Input N1, N2, N3 Step 2: if (N1>N2) then if (N1>N3) then MAX N1 [N1>N2, N1>N3] else MAX N3 [N3>N1>N2] endif else if (N2>N3) then MAX N2 [N2>N1, N2>N3] else MAX N3 [N3>N2>N1] endif endif Step 3: Print “The largest number is”, MAX
  • 27. Example 6 • Flowchart: Draw the flowchart of the above Algorithm.
  • 28. Example 7 • Write and algorithm and draw a flowchart to a) read an employee name (NAME), overtime hours worked (OVERTIME), hours absent (ABSENT) and b) determine the bonus payment (PAYMENT).
  • 29. Example 7 Bonus Schedule OVERTIME – (2/3)*ABSENT Bonus Paid >40 hours $50 >30 but 40 hours $40 >20 but 30 hours $30 >10 but 20 hours $20 10 hours $10
  • 30. Step 1: Input NAME,OVERTIME,ABSENT Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then PAYMENT 50 else if (OVERTIME–(2/3)*ABSENT > 30) then PAYMENT 40 else if (OVERTIME–(2/3)*ABSENT > 20) then PAYMENT 30 else if (OVERTIME–(2/3)*ABSENT > 10) then PAYMENT 20 else PAYMENT 10 endif Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
  • 31. Example 7 • Flowchart: Draw the flowchart of the above algorithm?
  • 32. Objectives • In this chapter you will be able to: • Introduce common words, keywords, and meaningful names when writing pseudocode • Define the three basic control structures as set out in the Structure Theorem • Illustrate the three basic control structures using pseudocode Simple Program Design, Fourth Edition 32 Chapter 2
  • 33. How to Write Pseudocode • When designing a solution algorithm, you need to keep in mind that a computer will eventually perform the set of instructions written • If you use words and phrases in the pseudocode which are in line with basic computer operations, the translation from pseudocode algorithm to a specific programming language becomes quite simple Simple Program Design, Fourth Edition 33 Chapter 2
  • 34. Six Basic Computer Operations 1 A computer can receive information – When a computer is required to receive information or input from a particular source, whether it is a terminal, a disk or any other device, the verbs Read and Get are used in pseudocode Example pseudocode Read student name Get system data Read => Input from a record Read number1, number2 Get tax_code Get => Input from keyboard Simple Program Design, Fourth Edition 34 Chapter 2
  • 35. Six Basic Computer Operations 1 A computer can receive information – Usually an output Prompt instruction is required before an input Get instruction Example pseudocode Prompt for student_mark Get student_mark Simple Program Design, Fourth Edition 35 Chapter 2
  • 36. Six Basic Computer Operations 2 A computer can put out information – When a computer is required to supply information or output to a device, the verbs Print, Write, Put, Output, or Display are used in pseudocode Example pseudocode Print ‘Program Completed’ – Print => send output to printer Write customer record to master Output total tax – Write => send out to file Display ‘End of data’ – Put, Output, Display => send to screen Simple Program Design, Fourth Edition 36 Chapter 2
  • 37. Six Basic Computer Operations 3 A computer can perform arithmetic – Most programs require the computer to perform some sort of mathematical calculation, or formula, and for these, a programmer may use either actual mathematical symbols or the words for those symbols – To be consistent with high-level programming languages, the following symbols can be written in pseudocode: + for Add - for Subtract * for Multiply / for Divide ( ) for Parentheses – When writing mathematical calculations for the computer, standard mathematical ‘order of operations’ applies to pseudocode and most computer languages Simple Program Design, Fourth Edition 37 Chapter 2
  • 38. Six Basic Computer Operations 4 A computer can assign a value to a variable or memory location – There are three cases where you may write pseudocode to assign a value to a variable or memory location: 1. To give data an initial value in pseudocode, the verbs Initialize or Set are used 2. To assign a value as a result of some processing the symbols ‘=‘ or ‘ ’ are written 3. To keep a variable for later use, the verbs Save or Store are used Simple Program Design, Fourth Edition 38 Chapter 2
  • 39. Six Basic Computer Operations 4 A computer can assign a value to a variable or memory location Example pseudocode Initialize total_price to zero Set student_count to zero Total_price = cost_price + sales_tax Total_price  cost_price + sales_tax Store customer_num in last_customer_num Simple Program Design, Fourth Edition 39 Chapter 2
  • 40. Six Basic Computer Operations 5 A computer can compare two variables and select one or two alternate actions – An important computer operation available to the programmer is the ability to compare two variables and then, as a result of the comparison, select one of two alternate actions – To represent this operation in pseudocode, special keywords are used: IF, THEN, and ELSE Simple Program Design, Fourth Edition 40 Chapter 2
  • 41. Six Basic Computer Operations 6 A computer can repeat a group of actions – When there is a sequence of processing steps that need to be repeated, two special keywords, DOWHILE and ENDDO, are used in pseudocode – The condition for the repetition of a group of actions is established in the DOWHILE clause, and the actions to be repeated are listed beneath it Simple Program Design, Fourth Edition 41 Chapter 2
  • 42. Meaningful Names • All names should be meaningful • A name given to a variable is simply a method of identifying a particular storage location in the computer • The uniqueness of a name will differentiate it from other locations • Often a name describes the type of data stored in a particular variable • Most programming languages do not tolerate a space in a variable name, as a space would signal the end of the variable name and thus imply that there were two variables Simple Program Design, Fourth Edition 42 Chapter 2
  • 43. The Structure Theorem • The Structure Theorem states that it is possible to write any computer program by using only three basic control structures that are easily represented in pseudocode: – Sequence – Selection – Repetition Simple Program Design, Fourth Edition 43 Chapter 2
  • 44. The Three Basic Control Structures 1 Sequence – The sequence control structure is the straightforward execution of one processing step after another – In pseudocode, we represent this construct as a sequence of pseudocode statements 2 Selection – The selection control structure is the presentation of a condition and the choice between two actions; the choice depends on whether the condition is true or false – In pseudocode, selection is represented by the keywords IF, THEN, ELSE, and ENDIF Simple Program Design, Fourth Edition 44 Chapter 2
  • 45. The Three Basic Control Structures 3 Repetition – The repetition control structure can be defined as the presentation of a set of instructions to be performed repeatedly, as long as a condition is true – The basic idea of repetitive code is that a block of statements is executed again and again, until a terminating condition occurs – This construct represents the sixth basic computer operation, namely to repeat a group of actions Simple Program Design, Fourth Edition 45 Chapter 2
  • 46. Summary • In this chapter, six basic computer operations were listed, along with pseudocode words and keywords to represent them • These operations were: to receive information, put out information, perform arithmetic, assign a value to a variable, decide between two alternate actions, and repeat a group of actions • The Structure Theorem was introduced; it states that it is possible to write any computer program by using only three basic control structures: sequence, selection, and repetition Simple Program Design, Fourth Edition 46 Chapter 2
  • 47. Someone Stole a Cookie from the Cookie Jar Problem: Momma had just filled the cookie jar when the 3 children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies, and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 3 cookies in the jar. How many cookies were in the jar to begin with?
  • 48. Someone Stole a Cookie from the Cookie Jar (cont’d) • Information available: – Three children – Each one ate half of the cookies – Three cookies remaining • Information needed: – Original number of cookies • Calculations: – For each child, multiply the number of remaining cookies by two.
  • 49. Specific Solution to the Problem • First, we solve the specific problem to help us identify the steps. – 3 cookies left X 2 = 6 cookies left after 2nd child – 6 X 2 = 12 cookies left after 1st child – 12 X 2 = 24 = original number of cookies
  • 50. A Generic Algorithm • What is a generic algorithm for this problem? An algorithm that will work with any number of remaining cookies AND that will work with any number of children.
  • 51. Generic Algorithm for Cookie Problem • Get number of children. • Get number of cookies remaining. • While there are still children that have not raided the cookie jar, multiply the number of cookies by 2 and reduce the number of children by 1. • Display the original number of cookies.
  • 52. Test The Generic Algorithm • Try the algorithm on paper with: – Four children and six cookies remaining. – Two children with two cookies remaining. • If you did not get the correct answer, modify the algorithm so that you get the correct answer.
  • 53. Pseudocode • When we broke down the previous problem into steps, we expressed each step as an English phrase. • We can think of this as writing pseudocode for the problem. • Typically, pseudocode is a combination of English phrases and formulas.
  • 54. Pseudocode (con’t) • Pseudocode is used in – designing algorithms – communicating an algorithm to the customer – converting an algorithm to code (used by the programmer) – debugging logic (semantic) errors in a solution before coding (hand tracing) • Let’s write the Cookie Problem algorithm using a more formal pseudocode and being more precise.
  • 55. Improved Pseudocode Display “Enter the number of children: “ Read <number of children> Display “Enter the number of cookies remaining: “ Read <cookies remaining> <original cookies> = <cookies remaining> While (<number of children> > 0) <original cookies> = <original cookies> X 2 <number of children> = <number of children> - 1 End_While Display “Original number of cookies = “, <original cookies>