SlideShare une entreprise Scribd logo
1  sur  46
Lecture 2
            Algorithms and
            Problem Solving




Computer Programming I        1
Overview
   Algorithm
   Program design
   Pseudocode
   Structure diagram
   Flowcharts
   Introduction to C++
   Testing and debugging
   Program errors
    Computer Programming I    2
Algorithm
 Algorithm
   A sequence of precise instructions which
    leads to a solution

 Program
   An algorithm expressed in a language the
    computer can understand



  Computer Programming I             3
Program Design
 Programming is a creative process
   No complete set of rules for creating a program

 Program Design Process
   Problem Solving Phase
     • Result is an algorithm that solves the problem
   Implementation Phase
     • Result is the algorithm translated into a programming
       language



   Computer Programming I                          4
Problem Solving Phase
 Be certain the task is completely specified
   What is the input?
   What information is in the output?
   How is the output organized?

 Develop the algorithm before implementation
   Experience shows this saves time in getting your
    program to run.
   Test the algorithm for correctness


   Computer Programming I                  5
Implementation Phase
 Translate the algorithm into a programming language
    Easier as you gain experience with the language

 Compile the source code
    Locates errors in using the programming language

 Run the program on sample data
    Verify correctness of results

 Results may require modification of the algorithm and
  program


   Computer Programming I                          6
Object Oriented Programming
 Abbreviated OOP

 Used for many modern programs

 Program is viewed as interacting objects
   Each object contains algorithms to describe
    its behavior
   Program design phase involves designing
    objects and their algorithms

  Computer Programming I             7
Sample problems
Write a program calculating the sum of two numbers
        Input                Processing           Output




        5, 10                                        15




   1) Declare variables                          3) Process
                             2) Assign values
   input_1                                       sum = input_1 + input_2
                             input_1 = 5
   input_2
                             input_2 = 10
   sum


                                                The computer (and so C++)
                Names for our cells
                                                provides basic arithmetic    8
                                                operations. If the operation
                                                you want to use is not provided,
                                                you have to compose it.
     Computer Programming I                              8
Write a program calculating the sum of two numbers

 There are many models supporting the
   development of the code. We will see now the
   same algorithm expressed as:

 1)Pseudocode
 2)Structure diagram
 3)Flowcharts


 and finally in C++.


    Computer Programming I            9
Pseudocode
 Mixture of C++ and ordinary English
 Allows us to make our algorithm precise
  without worrying about the details of C++
  syntax




  Computer Programming I          10
Pseudocode
Write a program calculating the sum of two numbers
  Version 1:                  Version 2:
  PROGRAM Add Two Numbers       PROGRAM Add Two Numbers
           READ two numbers         READ First
           ADD the numbers          READ Second
           WRITE the sum            Sum = First + Second
  END PROGRAM                       WRITE Sum
                                END PROGRAM




    Computer Programming I                 11
Structure Diagram
  Helpful to break the algorithm into more
   manageable pieces

Write a program calculating the sum of two numbers
   Version 1:      PROGRAM
                Add Two Numbers


      READ            ADD          WRITE
  Two Numbers     Two Numbers     The Sum



    Computer Programming I                  12
Structure Diagram
Write a program calculating the sum of two numbers

 Version 2:                          PROGRAM
                                  Add Two Numbers


                      READ              ADD           WRITE
                   Two Numbers      Two Numbers      The Sum


               READ       READ            Sum =
              Input_1   Input_2      Input_1 + Input_2




     Computer Programming I                         13
Rules for Structure Diagram
 A module which resides above others is
  referred to as a Calling module
 A module which resides below another is
  referred to as a Called module
 A module can be both a calling and called
  module
 A called module can only be called by one
  calling module

   Computer Programming I          14
Flowchart
 Diagram that shows the logical flow of a program
 Stress on structured programming
 Useful for planning each operation a program
  performs, and in order in which the operations
  are to occur
 By visualizing the process, a flowchart can
  quickly help identify bottlenecks or inefficiencies
  where the process can be streamlined or
  improved
 The final visualization can then be easily
  translated into a program
   Computer Programming I               15
Flowcharting symbols
      Input/Output (used for all I/O operations)

      Processing (used for all arithmetic and data transfer
      operations).

      Decision (used to test for a condition).


      Terminal (used to indicate the beginning and end of a
      program or module).

      Connector (used to indicate the point at which a transfer of
      control operation occurs).

      Predefined (used to indicate the name process of a module
      to be executed).

      Connecting all the symbols and showing the flow


Computer Programming I                              16
Write a program calculating the sum of two numbers
                        START


                      READ First
                     READ Second


                 Sum = First + Second


                     WRITE Sum


                         END

    Computer Programming I              17
Flowchart Conventions
1)   Each symbol denotes a type of operation.
2)   A note is written inside each symbol to indicate the
     specific function to be performed.
3)   The symbols are connected by flow-lines.
4)   Flowcharts are drawn and read from top to bottom
     unless a specific condition is met that alters the path.
5)   A sequence of operations is performed until a terminal
     symbol designates the sequence's end or the end of the
     program.
6)   Sometimes several steps or statements are combined
     in a single processing symbol for ease of reading.

     Computer Programming I                   18
Computer Programming I   19
start
A flowchart to accept two numbers as
    input and prints out the maximum
                                               Input A


                                               Input B

                                       False                   True
                                                 A>B



                                  print B                     print A




                                                  end




     Computer Programming I                              20
Structured Programming
   Structured Programming is a technique using logical control constructs
    that make programs easier to read, debug, and modify if changes are
    required.

                      true               false




                                                             true




    Sequence                 Selection               Repetition



      Computer Programming I                           21
Different selection structures
If a > 10 then do S1               If a > 10 then do nothing else do S2

                                                       false              true
true              false                                         A>10
        A>10


S1                                                     S2




 If a > 10 then do S1 else do S2    If a <= 10 then do S1

                                       True                 False
           true            false
                   A>10                        A<=10



          S1                 S2        S1




       Computer Programming I                           22
Loop structures
                                                              False
          S1                                    A<=10

                                                       true
          S2
                                                  S1

                  true
         A<=10
                                                  S2

               False
Repeat                              While A is less than or equal to
S1                                  10 repeat

S2                                  S1

As long as A is Less than or        S2
equal to 10 otherwise exit the      End loop
loop




     Computer Programmingthe
              What is I           difference ?
                                           23
Loop example (do..While)
Draw a flowchart to allow the input of 5 numbers                                   Start
and displays out the sum of these numbers
                                                                       1          C=1
                         Assume the numbers given to A
                         are 3,2,4,5,6 in order
                                                                       2         Sum=0

                     C=1             C=1             C=2
   C=1
                   Sum = 0         Sum = 3         Sum = 3
 Sum = 0
                     A=3             A=3             A=3
                                                                       3         Input A
  1,2                3                 4               5
                                                                       4        Sum = Sum + A


       C=2                     C=2             C=2             C=3
     Sum = 3                 Sum = 3         Sum = 5         Sum = 5   5        C=C+1
       A=3                     A=2             A=2             A=2
    C <=5 true
                                                                                                true
               6               3               4                  5    6           c<=5
                                                                                           False
     C=3                    C=3              C=3             C=4                  Output
   Sum = 5                Sum = 5          Sum = 9         Sum = 9     7           Sum
     A=3                    A=4              A=4             A=4
  C <=5 true
   Computer Programming 4
        6       3       I                                     5            24      End
Loop example (while…)
    Draw a flowchart to allow the input of                     Start
    5 numbers and displays out the sum
    of these numbers
                                                      1       C=1

1      C=1              Assume the numbers given to
                                                      2       Sum=0
                        A are 3,2,4,5,6 in order


2      C=1
                                                                            False
     Sum = 0                                          3       c<=5
                    4           5          6
                                                                     true
3
       C=1         C=1         C=1        C=2         4
     Sum = 0     Sum = 3     Sum = 3    Sum = 3               Input A
    C <=5 true     A=3         A=3        A=3
                                                      5    Sum = Sum + A


       C=2         C=2         C=2        C=3         6     C=C+1
     Sum = 3     Sum = 3     Sum = 5    Sum = 5
    C <=5 true     A=2         A=2        A=3
                                                             Output
        3           4            5         6          7       Sum

     Computer Programming I                           25       End
Prime number example flowchart
                                                             Start                 1
Pseudocode algorithm to solve
  this problem:                                          Input M                   2
1. Start                                                                           3
                                                             I=2
2. Input a number M
3. Set an Index (I) to start from 2
4. Divide the number M by the Index (I)                  R=M%I                     4
    value and store the remainder in R                               True
                                                False
5. If R is equal to zero then output “Not                    R=0?                  5
     Prime” and goto to Step 10
6. Increment Index (I) by 1                         I=I+1                          6
7. If the Index (I) value is less than the   True
     number M go to Step 4                          I<M?                           7

8. Output “Prime”                                            False
9. End                                              Output              Output     8
                                                     Prime             Not Prime




                                                             End                   9
           Computer Programming I                             26
Example of structured flowchart




Computer Programming I          27
Find the Maximum




                   28
Find the Maximum - Structured




                       29
Find the Maximum - Structured




                       30
Unstructured Flowchart




                                break…

Computer Programming I     31
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(Basic Combined
    Programming Language) language

 Why the ‘++’?
  ++ is an operator in C++

   Computer Programming I          32
C++ History
 C developed by Dennis Ritchie at
  AT&T(American Telephone & Telegraph
  Company) 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++

   Computer Programming I                 33
A Sample C++ Program
 A simple C++ program begins this way

     #include <iostream>
     using namespace std;
     int main()
     {

 And ends this way

           return 0;
     }

   Computer Programming I           34
Comments
Comments are pieces of source code discarded from the code by the
compiler. They do nothing. Their purpose is only to allow the programmer
to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment
/* block comment */
/* my second program in C++
   with more comments */
#include <iostream.h>
int main ()
{
    cout << "Hello World! "; // says Hello World!
    return 0;
}

     Computer Programming I                          35
My first program in C++               Hello World!

        a comment line

                                     a pound sign (#) is a directive for
                                     the preprocessor. It is not
 // my first program in C++          executable code but indications
                                     for the compiler.
 #include <iostream.h>
                                   tells the compiler's preprocessor to
 int main ()                       include the iostream standard header
                                   file.
 {
     cout << "Hello World!";       Corresponds to the beginning of the
                                   main function declaration. The main
     return 0;                     function is the point where all C++
                                   programs begin their execution.
 }

  to terminate a program       cout is the standard output stream in C++
     Computer Programming I                       36
Layout of a Simple C++ Program
           #include <iostream>
           using namespace std;

           int main()
           {
               variable_declarations

               statement_1
               statement_2
               …
               statement_last

               return 0;
           }

Computer Programming I                 37
Program Layout (1/2)
 Programmers format programs so they
  are easy to read
   Place opening brace ‘{‘ and closing brace ‘}’
     on a line by themselves
   Indent statements
   Use only one statement per line




  Computer Programming I              38
Program Layout (2/2)
 Variables are declared before they are used
   Typically variables are declared at the beginning of
    the program
   Statements (not always lines) end with a semi-colon

 Include Directives
         #include <iostream>
   Tells compiler where to find information about items
    used in the program
   iostream is a library containing definitions of cin and
    cout

   Computer Programming I                     39
Program Layout
using namespace std;
      Tells the compiler to use names in iostream in
       a “standard” way

      To begin the main function of the program
int main()
{
      To end the main function
return 0;
}
      Main function ends with a return statement
   Computer Programming I                  40
Running a C++ Program
 C++ source code is written with a text editor

 The compiler on your system converts
  source code to object code.

 The linker combines all the object code
  into an executable program.



   Computer Programming I            41
Concepts
Compiler: is a program that translates a high-level
language program, such as a C++ program, into a
machine-language program that the computer can
directly understand and execute.
Linking: The object code for your C++ program
must be combined with the object code for
routines (such as input and output routines) that
your program uses. This process of combining
object code is called linking and is done by a
program called a linker. For simple programs,
linking may be done for you automatically.
  Computer Programming I              42
Run a Program
 Obtain code
 Compile the code
 Fix any errors the compiler indicates and
  re-compile the code
 Run the program
 Now you know how to run a program on
  your system

  Computer Programming I          43
Testing and Debugging
 Bug
   A mistake in a program
 Debugging
   Eliminating mistakes in programs
   Term used when a moth caused a failed relay
    on the Harvard Mark 1 computer. Grace Hopper
    and other programmers taped the moth in logbook
    stating:
          “First actual case of a bug being found.”



  Computer Programming I                 44
Program Errors
 Syntax errors
   Violation of the grammar rules of the language
   Discovered by the compiler
     • Error messages may not always show correct location of
       errors
 Run-time errors
   Error conditions detected by the computer at run-time
 Logic errors (warning)
   Errors in the program’s algorithm
   Most difficult to diagnose
   Computer does not recognize an error


   Computer Programming I                        45
End of Lecture 2




Computer Programming I      46

Contenu connexe

Tendances

Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowchartsnicky_walters
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examplesGautam Roy
 
Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture AqsaHayat3
 
Introduction to basic programming
Introduction to basic programmingIntroduction to basic programming
Introduction to basic programmingJordan Delacruz
 
Introduction to programming concepts
Introduction to programming conceptsIntroduction to programming concepts
Introduction to programming conceptshermiraguilar
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networkingJafar Nesargi
 
How to Work with Dev-C++
How to Work with Dev-C++How to Work with Dev-C++
How to Work with Dev-C++Deepak Jha
 
Pseudocode & flowchart examples
Pseudocode & flowchart examplesPseudocode & flowchart examples
Pseudocode & flowchart exampleshayrikk
 
Theory of programming
Theory of programmingTheory of programming
Theory of programmingtcc_joemarie
 
SPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartSPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartMohammad Imam Hossain
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowchartsSamuel Igbanogu
 
Application Development and Emerging Technologies.pptx
Application Development and Emerging Technologies.pptxApplication Development and Emerging Technologies.pptx
Application Development and Emerging Technologies.pptxKENNEDYDONATO1
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchartJordan Delacruz
 
Binary number system
Binary number systemBinary number system
Binary number systemNadeem Uddin
 

Tendances (20)

Pseudocode
PseudocodePseudocode
Pseudocode
 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examples
 
Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture
 
Introduction to basic programming
Introduction to basic programmingIntroduction to basic programming
Introduction to basic programming
 
Introduction to programming concepts
Introduction to programming conceptsIntroduction to programming concepts
Introduction to programming concepts
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networking
 
How to Work with Dev-C++
How to Work with Dev-C++How to Work with Dev-C++
How to Work with Dev-C++
 
Introduction to computing
Introduction to computingIntroduction to computing
Introduction to computing
 
Pseudocode & flowchart examples
Pseudocode & flowchart examplesPseudocode & flowchart examples
Pseudocode & flowchart examples
 
Theory of programming
Theory of programmingTheory of programming
Theory of programming
 
SPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartSPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and Flowchart
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Application Development and Emerging Technologies.pptx
Application Development and Emerging Technologies.pptxApplication Development and Emerging Technologies.pptx
Application Development and Emerging Technologies.pptx
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchart
 
Programming
ProgrammingProgramming
Programming
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Binary number system
Binary number systemBinary number system
Binary number system
 

En vedette

Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programmingNoel Malle
 
Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01hassaanciit
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languagesVarun Garg
 
computer fundamental bba/bca/bba(FT)/B.com(CA)
computer fundamental bba/bca/bba(FT)/B.com(CA)computer fundamental bba/bca/bba(FT)/B.com(CA)
computer fundamental bba/bca/bba(FT)/B.com(CA)Dr. Sanjay Maheshwari
 
B08 jonathan bowen_alan_turing
B08 jonathan bowen_alan_turingB08 jonathan bowen_alan_turing
B08 jonathan bowen_alan_turingevaminerva
 
It 405 materi 2 java dasar
It 405 materi 2   java dasarIt 405 materi 2   java dasar
It 405 materi 2 java dasarAyi Purbasari
 
The History of computers
The History of computersThe History of computers
The History of computerskasrya62
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programmingNSU-Biliran Campus
 
Basic Computer Programming
Basic Computer ProgrammingBasic Computer Programming
Basic Computer ProgrammingAllen de Castro
 

En vedette (20)

Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Computer Programming- Lecture 11
Computer Programming- Lecture 11Computer Programming- Lecture 11
Computer Programming- Lecture 11
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languages
 
computer fundamental bba/bca/bba(FT)/B.com(CA)
computer fundamental bba/bca/bba(FT)/B.com(CA)computer fundamental bba/bca/bba(FT)/B.com(CA)
computer fundamental bba/bca/bba(FT)/B.com(CA)
 
B08 jonathan bowen_alan_turing
B08 jonathan bowen_alan_turingB08 jonathan bowen_alan_turing
B08 jonathan bowen_alan_turing
 
It 405 materi 2 java dasar
It 405 materi 2   java dasarIt 405 materi 2   java dasar
It 405 materi 2 java dasar
 
The History of computers
The History of computersThe History of computers
The History of computers
 
Lecture 1 report writing
Lecture 1 report writingLecture 1 report writing
Lecture 1 report writing
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
Basic Computer Programming
Basic Computer ProgrammingBasic Computer Programming
Basic Computer Programming
 
Computer programming concepts
Computer programming conceptsComputer programming concepts
Computer programming concepts
 
Activity 3 history of computer
Activity 3   history of computerActivity 3   history of computer
Activity 3 history of computer
 

Similaire à Computer Programming - Lecture 2

Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++Seble Nigussie
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesLiemLe21
 
Lecture01
Lecture01Lecture01
Lecture01Xafran
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c languagekamalbeydoun
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsOMWOMA JACKSON
 
C++ Overview
C++ OverviewC++ Overview
C++ Overviewkelleyc3
 
Computer and programing basics.pptx
Computer and programing basics.pptxComputer and programing basics.pptx
Computer and programing basics.pptxgaafergoda
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptxDineshDhuri4
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxNoorAntakia
 
learn computer science.ppt
learn computer science.pptlearn computer science.ppt
learn computer science.pptfaithola1
 
Introduction to computer science
Introduction to computer scienceIntroduction to computer science
Introduction to computer scienceumardanjumamaiwada
 

Similaire à Computer Programming - Lecture 2 (20)

2621008 - C++ 1
2621008 -  C++ 12621008 -  C++ 1
2621008 - C++ 1
 
Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languages
 
CHAPTER 1
CHAPTER 1CHAPTER 1
CHAPTER 1
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
Lecture01
Lecture01Lecture01
Lecture01
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Computer and programing basics.pptx
Computer and programing basics.pptxComputer and programing basics.pptx
Computer and programing basics.pptx
 
Savitch ch 01
Savitch ch 01Savitch ch 01
Savitch ch 01
 
Savitch ch 01
Savitch ch 01Savitch ch 01
Savitch ch 01
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
P3
P3P3
P3
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
 
learn computer science.ppt
learn computer science.pptlearn computer science.ppt
learn computer science.ppt
 
lecture 5
 lecture 5 lecture 5
lecture 5
 
Introduction to computer science
Introduction to computer scienceIntroduction to computer science
Introduction to computer science
 
PPS Unit-1.pdf
PPS Unit-1.pdfPPS Unit-1.pdf
PPS Unit-1.pdf
 

Computer Programming - Lecture 2

  • 1. Lecture 2 Algorithms and Problem Solving Computer Programming I 1
  • 2. Overview  Algorithm  Program design  Pseudocode  Structure diagram  Flowcharts  Introduction to C++  Testing and debugging  Program errors Computer Programming I 2
  • 3. Algorithm  Algorithm  A sequence of precise instructions which leads to a solution  Program  An algorithm expressed in a language the computer can understand Computer Programming I 3
  • 4. Program Design  Programming is a creative process  No complete set of rules for creating a program  Program Design Process  Problem Solving Phase • Result is an algorithm that solves the problem  Implementation Phase • Result is the algorithm translated into a programming language Computer Programming I 4
  • 5. Problem Solving Phase  Be certain the task is completely specified  What is the input?  What information is in the output?  How is the output organized?  Develop the algorithm before implementation  Experience shows this saves time in getting your program to run.  Test the algorithm for correctness Computer Programming I 5
  • 6. Implementation Phase  Translate the algorithm into a programming language  Easier as you gain experience with the language  Compile the source code  Locates errors in using the programming language  Run the program on sample data  Verify correctness of results  Results may require modification of the algorithm and program Computer Programming I 6
  • 7. Object Oriented Programming  Abbreviated OOP  Used for many modern programs  Program is viewed as interacting objects  Each object contains algorithms to describe its behavior  Program design phase involves designing objects and their algorithms Computer Programming I 7
  • 8. Sample problems Write a program calculating the sum of two numbers Input Processing Output 5, 10 15 1) Declare variables 3) Process 2) Assign values input_1 sum = input_1 + input_2 input_1 = 5 input_2 input_2 = 10 sum The computer (and so C++) Names for our cells provides basic arithmetic 8 operations. If the operation you want to use is not provided, you have to compose it. Computer Programming I 8
  • 9. Write a program calculating the sum of two numbers There are many models supporting the development of the code. We will see now the same algorithm expressed as: 1)Pseudocode 2)Structure diagram 3)Flowcharts and finally in C++. Computer Programming I 9
  • 10. Pseudocode  Mixture of C++ and ordinary English  Allows us to make our algorithm precise without worrying about the details of C++ syntax Computer Programming I 10
  • 11. Pseudocode Write a program calculating the sum of two numbers Version 1: Version 2: PROGRAM Add Two Numbers PROGRAM Add Two Numbers READ two numbers READ First ADD the numbers READ Second WRITE the sum Sum = First + Second END PROGRAM WRITE Sum END PROGRAM Computer Programming I 11
  • 12. Structure Diagram  Helpful to break the algorithm into more manageable pieces Write a program calculating the sum of two numbers Version 1: PROGRAM Add Two Numbers READ ADD WRITE Two Numbers Two Numbers The Sum Computer Programming I 12
  • 13. Structure Diagram Write a program calculating the sum of two numbers Version 2: PROGRAM Add Two Numbers READ ADD WRITE Two Numbers Two Numbers The Sum READ READ Sum = Input_1 Input_2 Input_1 + Input_2 Computer Programming I 13
  • 14. Rules for Structure Diagram  A module which resides above others is referred to as a Calling module  A module which resides below another is referred to as a Called module  A module can be both a calling and called module  A called module can only be called by one calling module Computer Programming I 14
  • 15. Flowchart  Diagram that shows the logical flow of a program  Stress on structured programming  Useful for planning each operation a program performs, and in order in which the operations are to occur  By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved  The final visualization can then be easily translated into a program Computer Programming I 15
  • 16. Flowcharting symbols Input/Output (used for all I/O operations) Processing (used for all arithmetic and data transfer operations). Decision (used to test for a condition). Terminal (used to indicate the beginning and end of a program or module). Connector (used to indicate the point at which a transfer of control operation occurs). Predefined (used to indicate the name process of a module to be executed). Connecting all the symbols and showing the flow Computer Programming I 16
  • 17. Write a program calculating the sum of two numbers START READ First READ Second Sum = First + Second WRITE Sum END Computer Programming I 17
  • 18. Flowchart Conventions 1) Each symbol denotes a type of operation. 2) A note is written inside each symbol to indicate the specific function to be performed. 3) The symbols are connected by flow-lines. 4) Flowcharts are drawn and read from top to bottom unless a specific condition is met that alters the path. 5) A sequence of operations is performed until a terminal symbol designates the sequence's end or the end of the program. 6) Sometimes several steps or statements are combined in a single processing symbol for ease of reading. Computer Programming I 18
  • 20. start A flowchart to accept two numbers as input and prints out the maximum Input A Input B False True A>B print B print A end Computer Programming I 20
  • 21. Structured Programming  Structured Programming is a technique using logical control constructs that make programs easier to read, debug, and modify if changes are required. true false true Sequence Selection Repetition Computer Programming I 21
  • 22. Different selection structures If a > 10 then do S1 If a > 10 then do nothing else do S2 false true true false A>10 A>10 S1 S2 If a > 10 then do S1 else do S2 If a <= 10 then do S1 True False true false A>10 A<=10 S1 S2 S1 Computer Programming I 22
  • 23. Loop structures False S1 A<=10 true S2 S1 true A<=10 S2 False Repeat While A is less than or equal to S1 10 repeat S2 S1 As long as A is Less than or S2 equal to 10 otherwise exit the End loop loop Computer Programmingthe What is I difference ? 23
  • 24. Loop example (do..While) Draw a flowchart to allow the input of 5 numbers Start and displays out the sum of these numbers 1 C=1 Assume the numbers given to A are 3,2,4,5,6 in order 2 Sum=0 C=1 C=1 C=2 C=1 Sum = 0 Sum = 3 Sum = 3 Sum = 0 A=3 A=3 A=3 3 Input A 1,2 3 4 5 4 Sum = Sum + A C=2 C=2 C=2 C=3 Sum = 3 Sum = 3 Sum = 5 Sum = 5 5 C=C+1 A=3 A=2 A=2 A=2 C <=5 true true 6 3 4 5 6 c<=5 False C=3 C=3 C=3 C=4 Output Sum = 5 Sum = 5 Sum = 9 Sum = 9 7 Sum A=3 A=4 A=4 A=4 C <=5 true Computer Programming 4 6 3 I 5 24 End
  • 25. Loop example (while…) Draw a flowchart to allow the input of Start 5 numbers and displays out the sum of these numbers 1 C=1 1 C=1 Assume the numbers given to 2 Sum=0 A are 3,2,4,5,6 in order 2 C=1 False Sum = 0 3 c<=5 4 5 6 true 3 C=1 C=1 C=1 C=2 4 Sum = 0 Sum = 3 Sum = 3 Sum = 3 Input A C <=5 true A=3 A=3 A=3 5 Sum = Sum + A C=2 C=2 C=2 C=3 6 C=C+1 Sum = 3 Sum = 3 Sum = 5 Sum = 5 C <=5 true A=2 A=2 A=3 Output 3 4 5 6 7 Sum Computer Programming I 25 End
  • 26. Prime number example flowchart Start 1 Pseudocode algorithm to solve this problem: Input M 2 1. Start 3 I=2 2. Input a number M 3. Set an Index (I) to start from 2 4. Divide the number M by the Index (I) R=M%I 4 value and store the remainder in R True False 5. If R is equal to zero then output “Not R=0? 5 Prime” and goto to Step 10 6. Increment Index (I) by 1 I=I+1 6 7. If the Index (I) value is less than the True number M go to Step 4 I<M? 7 8. Output “Prime” False 9. End Output Output 8 Prime Not Prime End 9 Computer Programming I 26
  • 27. Example of structured flowchart Computer Programming I 27
  • 29. Find the Maximum - Structured 29
  • 30. Find the Maximum - Structured 30
  • 31. Unstructured Flowchart break… Computer Programming I 31
  • 32. 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(Basic Combined Programming Language) language  Why the ‘++’? ++ is an operator in C++ Computer Programming I 32
  • 33. C++ History  C developed by Dennis Ritchie at AT&T(American Telephone & Telegraph Company) 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++ Computer Programming I 33
  • 34. A Sample C++ Program  A simple C++ program begins this way #include <iostream> using namespace std; int main() {  And ends this way return 0; } Computer Programming I 34
  • 35. Comments Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: // line comment /* block comment */ /* my second program in C++ with more comments */ #include <iostream.h> int main () { cout << "Hello World! "; // says Hello World! return 0; } Computer Programming I 35
  • 36. My first program in C++ Hello World! a comment line a pound sign (#) is a directive for the preprocessor. It is not // my first program in C++ executable code but indications for the compiler. #include <iostream.h> tells the compiler's preprocessor to int main () include the iostream standard header file. { cout << "Hello World!"; Corresponds to the beginning of the main function declaration. The main return 0; function is the point where all C++ programs begin their execution. } to terminate a program cout is the standard output stream in C++ Computer Programming I 36
  • 37. Layout of a Simple C++ Program #include <iostream> using namespace std; int main() { variable_declarations statement_1 statement_2 … statement_last return 0; } Computer Programming I 37
  • 38. Program Layout (1/2)  Programmers format programs so they are easy to read  Place opening brace ‘{‘ and closing brace ‘}’ on a line by themselves  Indent statements  Use only one statement per line Computer Programming I 38
  • 39. Program Layout (2/2)  Variables are declared before they are used  Typically variables are declared at the beginning of the program  Statements (not always lines) end with a semi-colon  Include Directives #include <iostream>  Tells compiler where to find information about items used in the program  iostream is a library containing definitions of cin and cout Computer Programming I 39
  • 40. Program Layout using namespace std;  Tells the compiler to use names in iostream in a “standard” way  To begin the main function of the program int main() {  To end the main function return 0; }  Main function ends with a return statement Computer Programming I 40
  • 41. Running a C++ Program  C++ source code is written with a text editor  The compiler on your system converts source code to object code.  The linker combines all the object code into an executable program. Computer Programming I 41
  • 42. Concepts Compiler: is a program that translates a high-level language program, such as a C++ program, into a machine-language program that the computer can directly understand and execute. Linking: The object code for your C++ program must be combined with the object code for routines (such as input and output routines) that your program uses. This process of combining object code is called linking and is done by a program called a linker. For simple programs, linking may be done for you automatically. Computer Programming I 42
  • 43. Run a Program  Obtain code  Compile the code  Fix any errors the compiler indicates and re-compile the code  Run the program  Now you know how to run a program on your system Computer Programming I 43
  • 44. Testing and Debugging  Bug  A mistake in a program  Debugging  Eliminating mistakes in programs  Term used when a moth caused a failed relay on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.” Computer Programming I 44
  • 45. Program Errors  Syntax errors  Violation of the grammar rules of the language  Discovered by the compiler • Error messages may not always show correct location of errors  Run-time errors  Error conditions detected by the computer at run-time  Logic errors (warning)  Errors in the program’s algorithm  Most difficult to diagnose  Computer does not recognize an error Computer Programming I 45
  • 46. End of Lecture 2 Computer Programming I 46