1 / 51

CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/

CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. Week 1: Problem-Solving and Algorithm. Computing Fundamentals Problem-Solving Algorithm Control Structures Tasks: Writing Algorithms in Pseudo-code. This symbol indicates the focus of today’s lesson.

dory
Download Presentation

CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/

  2. Week 1: Problem-Solving and Algorithm • 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)

  3. Computing Fundamentals Hardware Houses processor, memory, buses, etc. Monitor and speaker (output) Software Keyboard and mouse (input) • Set of instructions to perform tasks • Programs are software CS1010 (AY2013/4 Semester 1)

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

  5. 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 • High-level Program to which computer can respond directly. Each instruction is a binary code that corresponds to a native instruction. Example: 0001001101101110 CS1010 (AY2013/4 Semester 1)

  6. 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 • High-level Symbolic languagefor coding machinelanguage instructions. Example: ADD A, B, C CS1010 (AY2013/4 Semester 1)

  7. 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 • High-level Detailed knowledge of the machine is not required. Uses a vocabulary and structure closer to the problem being solved. Examples: Java, C, C++, Prolog, Scheme. CS1010 (AY2013/4 Semester 1)

  8. 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 • Interpreter • A translator that both translates and executes a source code CS1010 (AY2013/4 Semester 1)

  9. Edit, Compile and Execute Source code produces Editor welcome.c e.g.: vimwelcome.c Executable code produces Compiler a.out e.g.: gccwelcome.c Output Execute produces Hello, welcome to CS1010! e.g.: a.out CS1010 (AY2013/4 Semester 1)

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

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

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

  13. Introductory Workshop • We will conduct an Intro Workshop on 16 August, Friday and 20 August, Tuesday • Optional for those who have attended the UNIX workshop conducted by CompClub. • 16 August is meant for students in all sectional groups except SG31 and SG32. • 20 August is meant for students in SG31 and SG32. • Very important, please attend and be punctual! • Please refer to IVLE forum “Intro Workshop” and sign up there. • Getting started guide: • Course website  Labs  Intro workshop  Getting Started with UNIX and CodeCrunch CS1010 (AY2013/4 Semester 1)

  14. Week 1: Problem-Solving and Algorithm • Computing Fundamentals • Problem-Solving • Algorithm • Control Structures • Tasks: Writing Algorithms in Pseudo-code CS1010 (AY2013/4 Semester 1)

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

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

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

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

  19. 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)

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

  21. Week 1: Problem-Solving and Algorithm • Computing Fundamentals • Problem-Solving • Algorithm • Control Structures • Tasks: Writing Algorithms in Pseudo-code CS1010 (AY2013/4 Semester 1)

  22. 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. Algorithm Recipe Manual Input Output CS1010 (AY2013/4 Semester 1)

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

  24. Find maximum and average of a list of numbers (1/2) The need to initialisevariables. • Pseudo-code 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 1 2 3 4 5 6 7 8 9 The need to indent. Are there any errors in this algorithm? CS1010 (AY2013/4 Semester 1)

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

  26. Week 1: Problem-Solving and Algorithm • Computing Fundamentals • Problem-Solving • Algorithm • Control Structures • Tasks: Writing Algorithms in Pseudo-code CS1010 (AY2013/4 Semester 1)

  27. Control structures • Sequence • E.g. Line 1-2 • Branching (selection) • E.g. Line 6-7 • Loop (repetition) • E.g. Line 3-7 sumcount 0 max 0 for each num entered, countcount + 1 sumsum + num if num > max then maxnum avesum / count print max, ave 1 2 3 4 5 6 7 8 9 CS1010 (AY2013/4 Semester 1)

  28. 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, short, long • Real numbers: float, double • Characters: char • Read up Lesson 1.4 in reference book on your own • A variable holds some data and it belongs to a data type and occupies some memory space, shown as a box in the following slides. CS1010 (AY2013/4 Semester 1)

  29. Algorithm A entervalues for num1, num2, num3 ave ( num1 + num2 + num3 ) / 3 print ave Algorithm B entervalues for num1, num2, num3 total  ( num1 + num2 + num3 ) avetotal / 3 print ave Variables used: num1 num2 num3 ave Variables used: num1 num2 num3 total ave Algorithm: Example #1 (1/2) Sequence • Example 1: Compute the average of three integers. 1 2 3 1 2 3 4 CS1010 (AY2013/4 Semester 1)

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

  31. Variables used: num1 num2 final1 final2 Algorithm: Example #2 (1/3) Selection • Example 2: Arrange two integers in increasing order. Algorithm A: entervalues for num1, num2 // Assign smaller number into final1, // largernumberinto final2 if (num1 < num2) thenfinal1num1 final2num2 elsefinal1num2 final2num1 // Transfervalues in final1, final2backtonum1, num2 num1final1 num2 final2 // Display sortedintegers printnum1, num2 1 2 3 4 5 6 7 8 9 CS1010 (AY2013/4 Semester 1)

  32. Variables used: num1 num2 temp Algorithm: Example #2 (2/3) Selection • Example 2: Arrange two integers in increasing order. Algorithm B: entervalues for num1, num2 // Swap the values in the variables if necessary if (num2 < num1) thentempnum1 num1num2 num2temp // Display sortedintegers printnum1, num2 1 2 3 4 5 6 CS1010 (AY2013/4 Semester 1)

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

  34. Variables used: n count ans Algorithm: Example #3 (1/2) Repetition • Example 3: Find the sum of positive integers up to n (assuming that n is a positive integer). Algorithm: entervalue for n // Initialise a counter count to 1, and ans to 0 count 1 ans 0 while (count <= n) do the following ansans+ count // add count toans countcount + 1 // increase count by 1 // Display answer printans 1 2 3 456 7 CS1010 (AY2013/4 Semester 1)

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

  36. Euclidean algorithm • First documented algorithm by Greek mathematician Euclid in 300 B.C. • To compute the GCD (greatest common divisor) of two integers. • Let A and B be integers with A > B ≥ 0. • If B = 0, then the GCD is A and algorithm ends. • 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. 2 4 8 4 2 0 4 0 CS1010 (AY2013/4 Semester 1)

  37. Step-wise Refinement (1/3) • From the examples, 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. • Step-wise refinement – break down a complex step into smaller steps. CS1010 (AY2013/4 Semester 1)

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

  39. 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 convert miles to kilometres • We refine step 2 to: 1. Read in distance (m) in miles // step 1: input 2. Convert the distance to kilometres// step 2: compute 2.1calculate k = m * 1.609 3. Print the distance (k) in kilometres// step 3: output CS1010 (AY2013/4 Semester 1)

  40. Week 1: Problem-Solving and Algorithm • Computing Fundamentals • Problem-Solving • Algorithm • Control Structures • Tasks: Writing Algorithms in Pseudo-code CS1010 (AY2013/4 Semester 1)

  41. 2a Task 1: Area of a circle (1/2) • Given the side of square as 2a, compute the area of its bounding circle. • What is the input? Side of square = 2a • What is the output? Area of circle, C • Any intermediate results to be computed? Radius r, since C can be calculated from it • How to obtain r? CS1010 (AY2013/4 Semester 1)

  42. r a a Task 1: Area of a circle (2/2) • Pythagoras’ theorem: • Area of circle P M O Q CS1010 (AY2013/4 Semester 1)

  43. Task 2: Coin change (1/3) • Given these 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 375 cents, 6 coins are needed. • Example 2: For 543 cents, 10 coins are needed. CS1010 (AY2013/4 Semester 1)

  44. Task 2: Coin change (2/3) • Given these 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. Amount to be changed in cents • What is the input? Total number of coins needed • What is the output? • Any intermediate results to be computed? Number of coins of each type needed CS1010 (AY2013/4 Semester 1)

  45. Task 2: Coin change (3/3) CS1010 (AY2013/4 Semester 1) Week1 - 45 

  46. Task 3: Breaking up an integer (1/2) • A common sub-task in many problems involving number manipulation 252040312 3 5 2 2 4 2 1 0 0 • Example: Given a single integer n, how do you compute the sum of all its digits? • The answer for the above example is 19 (2 + 5 + 2 + 0 + 4 + 0 + 3 + 1 + 2) CS1010 (AY2013/4 Semester 1) Week1 - 46

  47. Task 3: Breaking up an integer (2/2) Integer • What is the input? • What is the output? Sum of the digits ofthe integer • Any intermediate results to be computed? Digits of the integer CS1010 (AY2013/4 Semester 1) Week1 - 47

  48. Algorithm before coding • The earlier 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 (AY2013/4 Semester 1)

  49. Summary for Today • Today’s most important lessons • Module objectives and resources • IVLE,Textbook • Problem-solving • As a systematic, logical process • Steps in problem-solving • Algorithms • Control structures: sequence, selection, repetition • How to write algorithms in pseudo-code CS1010 (AY2013/4 Semester 1)

  50. 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; optional if you have attended that) and sign up for it • Read “CS1010 Student Handbook” • Revise Chapter 1 Programming Fundamentals • Preparation for next week: • 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 CS1010 (AY2013/4 Semester 1)

More Related