CS1010: Programming Methodology http://www.comp.nus.edu.

sg/~cs1010/

Week 1: Problem-Solving and Algorithm
1. 2. 3. 4. 5. Computing Fundamentals Problem-Solving Algorithm Control Structures Tasks: Writing Algorithms in Pseudo-code

This symbol indicates the focus of today’s lesson.
CS1010 (AY2013/4 Semester 1)

Week1 - 2

Computing Fundamentals
Monitor and speaker (output) Houses processor, memory, buses, etc.

Keyboard and mouse (input)

 Set of instructions to perform tasks to specifications  Programs are software
Week1 - 3

CS1010 (AY2013/4 Semester 1)

Software (1/4)

Program

Sequence of instruction that tells a computer what to do Performing the instruction sequence Language for writing instructions to a computer Machine language or object code Assembly language High-level


 

Execution

Programming language

Major flavors
  

CS1010 (AY2013/4 Semester 1)

Week1 - 4

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

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

Software (4/4)  Program  Sequence of instruction that tells a computer what to do Performing the instruction sequence Language for writing instructions to a computer Machine language or object code Assembly language Detailed knowledge of the machine is not required. C. Uses a vocabulary High-level Examples: Java. Scheme. CS1010 (AY2013/4 Semester 1) Week1 . Prolog.    Execution  Programming language  Major flavors    and structure closer to the problem being solved.7 . C++.

Translation   High-level language programs (source codes) 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 A translator that both translates and executes a source code  Interpreter  CS1010 (AY2013/4 Semester 1) Week1 .8 .

c produces a.9 .Edit.c produces Source code welcome. welcome to CS1010! CS1010 (AY2013/4 Semester 1) Week1 .c Executable code Compiler eg: gcc welcome. Compile and Execute Editor eg: vim welcome.out Output produces Hello.out Execute eg: a.

You will need your UNIX account user-name and password.10 .sg/~newacct We will do a quick demonstration now.edu. To create SoC UNIX account: https://mysoc.nus.   CS1010 (AY2013/4 Semester 1) Week1 .Logging into UNIX system (1/3)   We will do more programming next week.

CS1010 (AY2013/4 Semester 1) Week1 . and double click on it.sg” for Host Name (or simply “sunfire” if you are using the PC in the lab) and your own user name as illustrated here.edu.11 . Look for the SSH Secure Shell Client icon on your desktop.Logging into UNIX system (2/3) 1. Enter “sunfire.comp. Click on “Quick Connect” to get the pop-up window.nus. 2. 3.

To log out from your UNIX account.12 . 6. you will see this screen (actual display may vary).Logging into UNIX system (3/3) 4. CS1010 (AY2013/4 Semester 1) Week1 . 5. type “exit” or “logout”. Enter your UNIX password. Once you log in successfully into your UNIX account.

Optional for those who have attended the UNIX workshop conducted by CompClub. please attend and be punctual!  Please refer to IVLE forum “Intro Workshop” and sign up there.Introductory Workshop  We will conduct an Intro Workshop on 16 August. Tuesday     Meant for students who did not attend the UNIX workshop conducted by CompClub. 16 August is meant for students in all sectional groups except SG31 and SG32. Friday and 20 August. Week1 . 20 August is meant for students in SG31 and SG32.13 CS1010 (AY2013/4 Semester 1) .  Very important.

Problem Solving Process Determine problem features Write algorithm Produce code Check for correctness and efficiency CS1010 (AY2013/4 Semester 1) Analysis Rethink as appropriate Design Implementation Testing Week1 .14 .

Your problem may be modest.15 . Such experiences at a susceptible age may create a taste for mental work and leave their imprint on mind and character for a lifetime. you may experience the tension and enjoy the triumph of discovery. – George Pólya CS1010 (AY2013/4 Semester 1) Week1 . and if you solve it by your own means.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. but if it challenges your curiosity and brings into play your inventive faculties.

 CS1010 (AY2013/4 Semester 1) Week1 .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.16 . Introduce suitable notation.

Split the problem into smaller sub-problems. If you can‟t solve it. or a special case.17    CS1010 (AY2013/4 Semester 1) .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. Week1 . solve a more general version. or part of it.

18 .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 (AY2013/4 Semester 1) Week1 .

or the method.19 .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. for some other problem? CS1010 (AY2013/4 Semester 1) Week1 .

as input.20 . and produces some value or set of values. Input Algorithm Output CS1010 (AY2013/4 Semester 1) Week1 . as output. that takes some value or set of values.Algorithmic Problem Solving  An algorithm is a well-defined computational procedure consisting of a set of instructions.

Can be presented in pseudo-code or flowchart. An algorithm must be effective.Algorithm      Each step of an algorithm must be exact. An algorithm must be general. An algorithm must terminate. Exact Terminate Effective General CS1010 (AY2013/4 Semester 1) Week1 .21 .

ave Are there any errors in this algorithm? CS1010 (AY2013/4 Semester 1) Week1 . // sum = sum of numbers // count = how many numbers are entered? // max to hold the largest value eventually for each num entered. count  count + 1 sum  sum + num The need to indent.22 .Find maximum and average of a list of numbers (1/2)  Pseudo-code sum  count  0 max  0 The need to initialise variables. if num > max then max  num ave  sum / count print max.

ave num > max? No Yes max  num end CS1010 (AY2013/4 Semester 1) Week1 .Find maximum and average of a list of numbers (1/2) Terminator box Process box sum  count  0 max  0  Flowchart start Decision box Yes end of input? No increment count sum  sum + num No ave  sum/count print max.23 .

Control structures  Sequence  Branching  Loop (selection) (repetition) CS1010 (AY2013/4 Semester 1) Week1 .24 .

Week1 . short. shown as a box in the following slides. double Characters: char  Read up Lesson 1.25 CS1010 (AY2013/4 Semester 1) . long Real numbers: float.4 in reference book on your own  A variable holds some data and it belongs to a data type and occupies some memory space.Data Representation  Internal representation: bits (binary digits) 0 and 1   1 byte = 8 bits We will not deal with bit level and bit operations  Data types (lists here are not exhaustive):    Integers: int.

num2.26 . num3 total  ( num1 + num2 + num3 ) ave  total / 3 print ave ave CS1010 (AY2013/4 Semester 1) Week1 .Algorithm: Example #1 (1/2)  Sequence Example 1: Compute the average of three integers. num2. num3 ave  ( num1 + num2 + num3 ) / 3 print ave ave Another possible algorithm: num1 Variables used: num2 total num3 enter values for num1. A possible algorithm: num1 Variables used: num2 num3 enter values for num1.

&num3).c // This program computes the average of 3 integers #include <stdio. num3.h> int main(void) { int num1. ave = (num1 + num2 + num3) / 3.27 . printf("Average = %.Algorithm: Example #1 (2/2)  Sequence How the code might look like Week1_prog1.0. scanf("%d %d %d". ave).2f\n". float ave. &num1. printf("Enter 3 integers: "). } CS1010 (AY2013/4 Semester 1) Week1 . num2. return 0. &num2.

Algorithm: Example #2 (1/3)  Algorithm A: enter values for num1. Variables used: num1 num2 final1 final2 // Transfer values in final1.28 . num2 // Assign smaller number into final1. num2 num1  final1 num2  final2 // Display sorted integers print num1. final2 back to num1. num2 CS1010 (AY2013/4 Semester 1) Week1 . // larger number into final2 if (num1 < num2) then final1  num1 final2  num2 else final1  num2 final2  num1 Selection Example 2: Arrange two integers in increasing order (sort).

Algorithm: Example #2 (2/3)  Algorithm B: enter values for num1. num2 Selection Example 2: Arrange two integers in increasing order (sort).29 . Variables used: num1 num2 temp CS1010 (AY2013/4 Semester 1) Week1 . num2 // Swap the values in the variables if necessary if (num2 < num1) then temp  num1 num1  num2 num2  temp // Display sorted integers print num1.

&num1. return 0. &num2). } printf("Sorted: num1 = %d. if (num2 < num1) { temp = num1. printf("Enter 2 integers: "). scanf("%d %d".30 . } CS1010 (AY2013/4 Semester 1) Week1 .c // This program arranges 2 integers in ascending order #include <stdio. num2 = temp. temp. num2. num2).h> int main(void) { int num1. num1. num2 = %d\n". num1 = num2.Algorithm: Example #2 (3/3)  Selection How the code might look like (for algorithm B) Week1_prog2.

Variables used: n count ans CS1010 (AY2013/4 Semester 1) Week1 .Algorithm: Example #3 (1/2)  Algorithm: enter value for n // Initialise a counter count to 1.31 . and ans to 0 count  1 ans  0 while (count <= n) do the following ans  ans + count // add count to ans count  count + 1 // increase count by 1 // Display answer print ans Repetition Example 3: Find the sum of positive integers up to n (assuming that n is a positive integer).

&n). // upper limit int count=1. count++. // initialisation printf("Enter n: "). ans).Algorithm: Example #3 (2/2)  Repetition Week1_prog3. scanf("%d". How the code might look like return 0. while (count <= n) { ans += count.c // Computes sum of positive integers up to n #include <stdio.32 . } printf("Sum = %d\n".h> int main(void) { int n. } CS1010 (AY2013/4 Semester 1) Week1 . ans=0.

Otherwise. CS1010 (AY2013/4 Semester 1) Week1 . 3. Replace A by B.33 . If B = 0. 2. Go to step 2.  To compute the GCD (greatest common divisor) of two integers. then the GCD is A and algorithm ends.C. and B by r.B + r where 0 ≤ r < B 4.Euclidean algorithm  First documented algorithm by Greek mathematician Euclid in 300 B. Let A and B be integers with A > B ≥ 0. 1. find q and r such that A = q.

CS1010 (AY2013/4 Semester 1) Week1 .Step-wise Refinement (1/3)  From the examples. Step-wise refinement – break down a complex step into smaller steps. we see that in general an algorithm comprises three steps:    Input (read data) Compute (process input data to generate some answers) Output (display answers)   The „compute‟ step is the most complex.34 .

ask questions!  One possible algorithm: 1. Print the distance (k) in kilometres // step 1: input // step 2: compute // step 3: output CS1010 (AY2013/4 Semester 1) Week1 . Convert the distance to kilometres (k) 3.   Is the problem clear? If not. Read in distance (m) in miles 2.35 . convert it into kilometres Recall Phase 1 of “How To Solve It”: Understanding the problem.Step-wise Refinement (2/3)  Example: Given a value in miles.

if we are clear about how to do each step.Step-wise Refinement (3/3)  We can actually stop here. If not. Convert the distance to kilometres 2. we need to refine the step. Read in distance (m) in miles 2.1 calculate k = m * 1. For instance.609 3.36 . how do we convert miles to kilometres   we refine step 2 to: // step 1: input // step 2: compute // step 3: output 1. step 2. Print the distance (k) in kilometres CS1010 (AY2013/4 Semester 1) Week1 .

37 .Tasks for practice on Problemsolving and writing Algorithms in Pseudo-code CS1010 (AY2013/4 Semester 1) Week1 .

Task 1: Area of a Circle (1/2)  What is the data? Side of square = 2a What is the unknown? Area of circle. How to obtain r?  CS1010 (AY2013/4 Semester 1) Week1 .38 . C can be calculated.  2a  What is the condition? If radius r is known. C.

39 .Task 1: Area of a Circle (2/2) a r a   Pythagoras‟ theorem: Area of circle  CS1010 (AY2013/4 Semester 1) Week1 .

20¢.Task 2: Coin Change  Given these coin denominations: 1¢.40 .   Example 1: For 375 cents. find the smallest number of coins needed for a given amount. 5¢. CS1010 (AY2013/4 Semester 1) Week1 . 50¢. Example 2: For 543 cents. and $1. 6 coins are needed. You do not need to list out what coins are used. 10 coins are needed. 10¢.

Task 2: Coin Change – A possible algorithm  CS1010 (AY2013/4 Semester 1) Week1 .41 .

how do you sum up all its individual digits?  The answer for the above example is 19 (2 + 5 + 2 + 0 + 4 + 0 + 3 + 1 + 2) CS1010 (AY2013/4 Semester 1) Week1 .Task 3: Breaking Up an Integer  A common sub-task in many problems involves number manipulation 252040312 2 5 2 4 3 1 2 0 0  Example: Given a positive integer n.42 .

time spent in thinking about the algorithm could far exceed time spent in writing the program.  CS1010 (AY2013/4 Semester 1) Week1 . the more time you will save in debugging your program.43 .Algorithm before coding  The earlier examples show that we can discuss problems and their solutions (algorithms) without writing out the codes. The more time you invest in writing a good algorithm. 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. A sample program development process:       Understanding the problem (if in doubt.

Every step must be clear to you.44 . 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.Quotes for CS1010 Students  Before you succeed.    CS1010 (AY2013/4 Semester 1) Week1 .

IVLE. CS1010 Handbook.45 CS1010 (AY2013/4 Semester 1) . repetition How to write algorithms in pseudo-codes Week1 . selection.Summary for Today  Today‟s most important lessons  Module objectives and resources  Module website.  Problem-solving   As a systematic. etc. logical process Steps in problem-solving  Algorithms   Control structures: sequence.

optional if you have attended that) and sign up for it Read “CS1010 Student Handbook” Revise Chapter 1 Programming Fundamentals Read Chapters 2 and 3 Learn vim and practise using it Create your UNIX account (if you have not done so) and bring along your UNIX password next week Week1 .46  Preparation for next week:    CS1010 (AY2013/4 Semester 1) .Announcements/Things-to-do  Reminders      Discussion classes start in week 3 Check module website and IVLE forums regularly Read IVLE forum about the Intro workshop (only for students who did not attend the one conducted by CompClub.

End of File .

Sign up to vote on this title
UsefulNot useful