Week1 by shitingting

VIEWS: 4 PAGES: 51

									CS1010: Programming Methodology
http://www.comp.nus.edu.sg/~cs1010/
 Week 1: Introduction
            Chapter 1: Computers and Computing
                Fundamentals
               High-level programming languages
               Useful problem-solving strategies.
               Writing algorithms in pseudo-codes.




CS1010 (AY2010/2011 Semester 1)                       Week1 - 2
 Chapter 1: Computers and Computing
 Fundamentals
     From Tan & D’Orazio’s book
     Please read up on your own




                                  Source codes
                                  available on module
                                  website

CS1010 (AY2010/2011 Semester 1)                         Week1 - 3
 Computers as Information Processors
 (1/2)
     Computer = Hardware + Software.
            Hardware: physical components for
                computation/processing; should be simple, fast,
                reliable.
            Software: set of instructions to perform tasks to
                specifications; should be flexible, user-friendly,
                sophisticated.
            Programs are thus software.



CS1010 (AY2010/2011 Semester 1)                                      Week1 - 4
 Computers as Information Processors
 (2/2)
    Computer are Information Processors
                       Raw                  Computer           Processed
                       data                  system           information


          Data units
                Internal representation in machine
                   o    1 bit (binary digit): 0 or 1
                   o    1 byte = 8 bits
                   o    Floating-point representation, etc.
                Data types in programs
                   o    int, char, float, etc.

CS1010 (AY2010/2011 Semester 1)                                             Week1 - 5
 Components of a Computer (1/2)
    Main Components:
           Processor (controls devices and processes data).
           Memory: stores programs and intermediate data.
           Input Devices: accept data from outside world.
           Output Devices: presents data to the outside world.

    An analogy with Human Information Processors:
           Processor – brain’s reasoning powers
           Memory – brain’s memory
           Input Devices – eyes, ears, sensory sub-system
           Output Devices – mouth, hands, facial and body
              expressions

CS1010 (AY2010/2011 Semester 1)                              Week1 - 6
  Components of a Computer (2/2)
Monitor and
speaker (output)




                                                   Contains processor,
                                                   memory, buses, etc.




                                   Keyboard and
                                   mouse (input)

 CS1010 (AY2010/2011 Semester 1)                                  Week1 - 7
 Software (1/4)
          Program
                Sequence of instruction that tells a computer what to do
          Execution
                Performing the instruction sequence
          Programming language
                Language for writing instructions to a computer
          Major flavors
                Machine language or object code
                Assembly language
                High-level




CS1010 (AY2010/2011 Semester 1)                                             Week1 - 8
 Software (2/4)
          Program
                Sequence of instruction that tells a computer what to do
          Execution
                Performing the instruction sequence
          Programming language
                Language for writing instructions to a computer
          Major flavors
                Machine language or object code
                Assembly language    Program to which computer can
                                     respond directly. Each instruction
                High-level
                                        is a binary code that corresponds
                                              to a native instruction.
                                        Example: 0001001101101110

CS1010 (AY2010/2011 Semester 1)                                             Week1 - 9
 Software (3/4)
          Program
                Sequence of instruction that tells a computer what to do
          Execution
                Performing the instruction sequence
          Programming language
                Language for writing instructions to a computer
          Major flavors
                Machine language or object code
                Assembly language               Symbolic language
                High-level                     for coding machine
                                                language instructions.
                                               Example: ADD A, B, C


CS1010 (AY2010/2011 Semester 1)                                             Week1 - 10
 Software (4/4)
          Program
                Sequence of instruction that tells a computer what to do
          Execution
                Performing the instruction sequence
          Programming language
                Language for writing instructions to a computer
          Major flavors
                Machine language or object code
                Assembly language Detailed knowledge of the machine
                High-level          is not required. Uses a vocabulary
                                      and structure closer to the problem
                                                 being solved.
                                          Examples: Java, C, C++,
                                             Prolog, Scheme.
CS1010 (AY2010/2011 Semester 1)                                             Week1 - 11
 Translation
          High-level language programs (source programs)
           must be translated into machine code for execution
          Translator
                Accepts a program written in a source language and
                 translates it to a program in a target language
          Compiler
                Standard name for a translator whose source language is
                 a high-level language
          Interpreter
                A translator that both translates and executes a source
                 program




CS1010 (AY2010/2011 Semester 1)                                            Week1 - 12
 Edit, Compile and Execute
                                                                  Source code
                                      Editor          produces
                                                                   welcome.c
                                  eg: vim welcome.c




                                                                 Executable code
                                    Compiler          produces
                                                                     a.out
                                  eg: gcc welcome.c




                                                                    Output

                                    Execute           produces    Hello,
                                      eg: a.out                   welcome to
                                                                  CS1010!




CS1010 (AY2010/2011 Semester 1)                                                    Week1 - 13
 Logging into UNIX system (1/3)
          We will do programming next week.
          For that, you need your UNIX account user-
           name and password.
          See module website  Misc.  For
           Freshmen  Creating your SoC UNIX
           account
          We will do a quick demonstration.




CS1010 (AY2010/2011 Semester 1)                    Week1 - 14
 Logging into UNIX system (2/3)
1. Look for the SSH Secure Shell
   Client icon on your desktop, and
   double click on it.

2. Click on “Quick Connect”
   to get the pop-up window.
   Enter
   “sunfire.comp.nus.edu.sg”
   for Host Name and your
   own user name as
   illustrated here.



 If you forget your user
 name and/or password,
 remember to get them
 for next week’s lecture!



CS1010 (AY2010/2011 Semester 1)       Week1 - 15
 Logging into UNIX system (3/3)
3. Enter your UNIX password.




4. Once you log in successfully into your UNIX account,
   you will see this screen (actual display may vary).



5. To log out from your
   UNIX account, type “exit”
   or “logout”.




CS1010 (AY2010/2011 Semester 1)                           Week1 - 16
 UNIX Workshop
          Have you attended the UNIX workshop conducted
           on 4 August (last Wednesday) organised by the
           Computing Club?
          If not, please attend the workshop this Thursday (12
           August) afternoon or next Monday (16 August)
           morning (conducted by Aaron).
          See the IVLE discussion forum for details.
          (Note: If you have already attended the one
           conducted by CompClub, you do not need to attend
           Aaron’s workshop.)



CS1010 (AY2010/2011 Semester 1)                             Week1 - 17
 Problem Solving Process
           Determine problem
                features             Analysis

                                                   Rethink as
              Write algorithm                      appropriate
                                     Design


               Produce code
                                  Implementation


         Check for correctness       Testing
            and efficiency

     Refer also to Jumpstart to SoC on module website,
      “Misc…”, “For Freshmen”.

CS1010 (AY2010/2011 Semester 1)                            Week1 - 18
 Pólya: How to Solve It (1/5)
        A great discovery solves a great problem but there is a
        grain of discovery in the solution of any problem.
        Your problem may be modest; but if it challenges your
        curiosity and brings into play your inventive faculties,
        and if you solve it by your own means, you may
        experience the tension and enjoy the triumph of
        discovery.
        Such experiences at a susceptible age may create a
        taste for mental work and leave their imprint on mind
        and character for a lifetime.
                                            – George Pólya


CS1010 (AY2010/2011 Semester 1)                             Week1 - 19
 Pólya: How to Solve It (2/5)
        Phase 1: Understanding the problem
        Phase 2: Devising a plan
        Phase 3: Carrying out the plan
        Phase 4: Looking back

                 What is the unknown? What are the data?
                 What is the condition? Is it possible to satisfy the
                  condition? Is the condition sufficient to determine the
                  unknown?
                 Draw a figure. Introduce suitable notation.



CS1010 (AY2010/2011 Semester 1)                                             Week1 - 20
 Pólya: How to Solve It (3/5)
        Phase 1: Understanding the problem
        Phase 2: Devising a plan
        Phase 3: Carrying out the plan
        Phase 4: Looking back

                 Have you seen the problem before? Do you know a related
                  problem?
                 Look at the unknown. Think of a problem having the same or
                  similar unknown.
                 Split the problem into smaller sub-problems.
                 If you can’t solve it, solve a more general version, or a
                  special case, or part of it.
CS1010 (AY2010/2011 Semester 1)                                               Week1 - 21
 Pólya: How to Solve It (4/5)
        Phase 1: Understanding the problem
        Phase 2: Devising a plan
        Phase 3: Carrying out the plan
        Phase 4: Looking back

                 Carry out your plan of the solution. Check each step.
                 Can you see clearly that the step is correct?
                 Can you prove that it is correct?




CS1010 (AY2010/2011 Semester 1)                                           Week1 - 22
 Pólya: How to Solve It (5/5)
        Phase 1: Understanding the problem
        Phase 2: Devising a plan
        Phase 3: Carrying out the plan
        Phase 4: Looking back

                 Can you check the result?
                 Can you derive the result differently?
                 Can you use the result, or the method, for some other
                  problem?




CS1010 (AY2010/2011 Semester 1)                                           Week1 - 23
 Algorithmic Problem Solving
        An algorithm is a well-defined computational
         procedure consisting of a set of instructions, that takes
         some value or set of values, as input, and produces
         some value or set of values, as output.


                      Input       Algorithm     Output




CS1010 (AY2010/2011 Semester 1)                              Week1 - 24
 Algorithm
        Each step of an algorithm must be exact.
        An algorithm must terminate.
        An algorithm must be effective.
        An algorithm must be general.
        Can be presented in pseudo-code or flowchart.




CS1010 (AY2010/2011 Semester 1)                          Week1 - 25
 Euclidean algorithm
        First documented algorithm by Greek mathematician
         Euclid in 300 B.C.
               To compute the GCD (greatest common divisor) of two integers.

           1. Let A and B be integers with A > B ≥ 0.
           2. If B = 0, then the GCD is A and algorithm ends.
           3. Otherwise, find q and r such that

                         A = q.B + r   where 0 ≤ r < B

           4. Replace A by B, and B by r. Go to step 2.




CS1010 (AY2010/2011 Semester 1)                                       Week1 - 26
 Find maximum and average of a list of numbers
 (1/3)
        Version 1
           Declare variables sum, count and max.
           First, you initialise sum, count and max to zero.
           Then, you enter the input numbers, one by one.
                    For each number that you have entered, assign it to num and
                    add it to the sum.
                    Increase count by 1.
                    At the same time, you compare num with max. If num is larger
                    than max, let max be num instead.
           After all the numbers have been entered, you divide sum by the
           numbers of items entered, and let ave be this result.
           Print max and ave.
           End of algorithm.

CS1010 (AY2010/2011 Semester 1)                                               Week1 - 27
 Find maximum and average of a list of numbers
 (2/3)
        Version 2
           sum  count  0        // sum = sum of numbers
                                  // count = how many numbers are entered?
           max  0                // max to hold the largest value eventually
           for each num entered,
                 count  count + 1
                 sum  sum + num
                 if num > max
                                then max  num

           ave  sum / count

           print max, ave



CS1010 (AY2010/2011 Semester 1)                                                 Week1 - 28
 Find maximum and average of a list of numbers
 (3/3)                                                                             Terminator box
                                                    start
        Flowchart
                                                                                   Process box
                                              sum  count  0
                                                 max  0
                                                                                   Decision box



                                        Yes        end of
                                                   input?

                                                  No
                                               increment count
                                              sum  sum + num
                     ave  sum/count

                                                  No


                       print max, ave                            Yes
                                                 num > max?            max  num


                                                  No
                            end




CS1010 (AY2010/2011 Semester 1)                                                                     Week1 - 29
 Handling a list (1/2)
        In the previous example, we compute the maximum as
         we read in the input numbers one by one.
        In many applications, it might be desirable to read in the
         whole list of numbers first, then we work on the list.
        To do this, we need to introduce some notation.
        Given a list A with n items, we may refer to the
         individual items as A0, A1, A2, …, An-1




CS1010 (AY2010/2011 Semester 1)                             Week1 - 30
 Handling a list (2/2)
        We can then write version 3:
            count  0              // count = how many numbers are entered?
            while not end of input
                  enter value for Acount
                  count  count + 1

            sum  0               // sum = sum of numbers
            max  0               // max to hold the largest value eventually
            for i from 0 to count – 1
                    sum  sum + Ai
                    if Ai > max
                                   then max  Ai
            ave  sum / count
            print max, ave

CS1010 (AY2010/2011 Semester 1)                                                 Week1 - 31
 Control structures
        Sequence
        Branching (selection)
        Loop (repetition)




CS1010 (AY2010/2011 Semester 1)   Week1 - 32
 Algorithm: Examples (1/4)
        Example 1: Compute the average of three integers.

          A possible algorithm:                               Variables used:

                                                       num1       num2      num3
                   enter values for num1, num2, num3
                   ave  ( num1 + num2 + num3 ) / 3                ave

                   print ave


          Another possible algorithm:                          Variables used:

                                                       num1        num2         num3
                   enter values for num1, num2, num3
                                                                    total
                   total  ( num1 + num2 + num3 )
                   ave  total / 3                                  ave
                   print ave



CS1010 (AY2010/2011 Semester 1)                                                    Week1 - 33
 Algorithm: Examples (2/4)
        Example 2: Arrange two integers in increasing order
         (sort).
          Algorithm A:                                                       Variables used:

                enter values for num1, num2                                  num1         num2
                   // Assign smaller number into final1,
                   // larger number into final2                              final1       final2

                   if (num1 < num2)
                       then final1  num1
                              final2  num2
                       else final1  num2
                              final2  num1
                   // Transfer values in final1, final2 back to num1, num2
                   num1  final1
                   num2  final2
                   // Display sorted integers
                   print num1, num2
CS1010 (AY2010/2011 Semester 1)                                                       Week1 - 34
 Algorithm: Examples (3/4)
        Example 2: Arrange two integers in increasing order
         (sort).
          Algorithm B:                                                Variables used:

                enter values for num1, num2                           num1          num2
                   // Swap the values in the variables if necessary
                   if (num2 < num1)                                          temp

                       then temp  num1
                            num1  num2
                            num2  temp
                   // Display sorted integers
                   print num1, num2




CS1010 (AY2010/2011 Semester 1)                                                 Week1 - 35
 Algorithm: Examples (4/4)
        Example 3: Find the sum of positive integers up to n
         (assuming that n is a positive integer).
          Algorithm:                                                      Variables used:

                enter value for n                                               n
                   // Initialise a counter count to 1, and ans to 0
                   count  1                                                  count

                   ans  0                                                     ans
                   while (count <= n) do the following
                         ans  ans + count       // add count to ans
                         count  count + 1       // increase count by 1
                   // Display answer
                   print ans




CS1010 (AY2010/2011 Semester 1)                                                      Week1 - 36
 Step-wise Refinement (1/3)
        From preceding examples, we can see that in general
         an algorithm comprises three steps:
               Input (read data (at the moment from user))
               Compute (process the input data to generate some answers)
               Output (display the answers)
        The ‘compute’ step is in general the most complex.
        Step-wise refinement – breaking down a complex step
         into smaller steps.




CS1010 (AY2010/2011 Semester 1)                                     Week1 - 37
 Step-wise Refinement (2/3)
        Example: Given a list A containing n integers, how
         would you find the second largest value in the list?
        Before we begin, remember Phase 1 of “How To Solve
         It”: Understanding the problem.
               Is the problem clear? If not, ask questions!
        One possible algorithm:
                    read values into A           // step 1: input
                    sort A in descending order   // step 2: compute
                    print A1                     // step 3: output




CS1010 (AY2010/2011 Semester 1)                                       Week1 - 38
 Step-wise Refinement (3/3)
        We can actually stop here, if we are clear about how to
         do each step.
        If not, we need to refine the step. For instance, step 2,
         how do we sort?
               We won’t discuss this now as sorting will be covered later.
        Can you solve this problem without using sorting?




CS1010 (AY2010/2011 Semester 1)                                          Week1 - 39
 Task 1: Area of a circle (1/2)

                                     What is the data? Side of
                                      square = 2a
                                     What is the unknown? Area
                        2a            of circle, C.
                                     What is the condition? If
                                      radius r is known, C can be
                                      calculated.
                                     How to obtain r?



CS1010 (AY2010/2011 Semester 1)                                   Week1 - 40
 Task 1: Area of a circle (2/2)

                             r           Pythagoras’ theorem:
                     a
                                              r2 = 2 * a2
                                  a
                                         Area of circle
                                              C =  * r2
                                                =  * 2 * a2




CS1010 (AY2010/2011 Semester 1)                                  Week1 - 41
 Task 2: Pascal’s triangle

        0                             Compute nCk or C(n,k)
            C0                    1



 3
    1
    C0      1 1
           1 2 1
         1 3 3 1
                     1
                       C1
                         n
                           Ck =
                                           {   n-1
                                                     Ck-1 + n-1Ck
                                               1, if k=0 or k=n
   C1
        1 4 6 4 1
       1 5 10 10 5 1

      5
          C3


CS1010 (AY2010/2011 Semester 1)                               Week1 - 42
 Task 3: NE-paths
        To find the number of north-east paths between any
         two points.
        North-east (NE) path: you may only move northward or
         eastward.
        How many NE-paths between A and C?
                                                   C

                                           A   A

                                           A



                                  A

CS1010 (AY2010/2011 Semester 1)                          Week1 - 43
 Task 4: Palindrome
        A word is a palindrome if it reads the same forward and
         backward.
               Examples: NOON, RADAR.
        How do you determine if a word W is a palindrome?




CS1010 (AY2010/2011 Semester 1)                           Week1 - 44
 Task 5: Anagrams
        Two phrases are anagrams if one is formed by
         rearranging the letters of the other, disregarding
         spaces and punctuation marks.
               Examples: “Debit card” = “Bad credit”; “The eyes” = “They
                see”; “Astronomer” = “Moon starer”; “A telescope” = “To see
                place”; “A decimal point” = “I’m a dot in place”.
        For our purpose, we’ll do a simpler version on words
         without spaces or punctuation marks, and all letters are
         in capital.
               Example: “LISTEN” = “SILENT”.
        How do you determine if two words X and Y are
         anagrams?
CS1010 (AY2010/2011 Semester 1)                                        Week1 - 45
 Task 6: Coin change
        Given this list of coin denominations: 1¢, 5¢, 10¢, 20¢,
         50¢, and $1, find the smallest number of coins needed
         for a given amount. You do not need to list out what
         coins are used.
               Example 1: For $3.75, 6 coins are needed.
               Example 2: For $5.43, 10 coins are needed.
        For simplicity, assume that the input data is in cents.




CS1010 (AY2010/2011 Semester 1)                              Week1 - 46
 Algorithm before coding
        Preceding examples show that we can discuss problems and their
         solutions (algorithms) without writing out the codes.
        A sample program development process:
               Understanding the problem (if in doubt, ask questions!): 5 minutes
               Writing the algorithm: 30 minutes
               Testing the algorithm: 20 minutes
               Writing the program: 20 minutes
               Testing and debugging the program: 30 minutes to 3 hours or more
        For more complex problems, time spent in thinking about the algorithm
         could far exceed time spent in writing the program.
        The more time you invest in writing a good algorithm, the more time you
         will save in debugging your program.


CS1010 (AY2010/2011 Semester 1)                                               Week1 - 47
 Quotes for CS1010 Students
        Before you succeed, you must fail many times.
        Don’t ask me what this code does, trace it
         yourself!
        Think! Think! Think!
        Practise! Practise! Practise!
        It’s all about logic. Every step must be clear to
         you.



CS1010 (AY2010/2011 Semester 1)                       Week1 - 48
 Summary for Today
        Today’s most important lessons
                 Module objectives and resources
                       Module website, IVLE, CS1010 Handbook, etc.
               Problem-solving
                       As a systematic, logical process
                       Steps in problem-solving

               Algorithms
                       How to write pseudo-codes
                       Control structures: sequence, selection, repetition



CS1010 (AY2010/2011 Semester 1)                                               Week1 - 49
 Announcements/Things-to-do
        Discussion classes start in week 3.
        Check out IVLE regularly for announcements and
         updates.
        Read Chapter 1 Computers and Computing
         Fundamentals
        To prepare for next week:
               Visit module website and IVLE
               Read IVLE forum about the UNIX workshop (only for
                students who did not attend the one conducted by
                CompClub)
               Read “CS1010 Handbook”
               Read Chapters 2 and 3
               Bring along your UNIX password for next week
CS1010 (AY2010/2011 Semester 1)                                     Week1 - 50
                                  End of File




CS1010 (AY2010/2011 Semester 1)                 Week1 - 51

								
To top