1 / 52

CS1010: Programming Methodology comp.nus.sg/~cs1010/

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

gerodi
Download Presentation

CS1010: Programming Methodology comp.nus.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 2 Part I: Introduction • Chapter 1: Computers and Computing Fundamentals • High-level programming languages • Useful problem-solving strategies. • Writing algorithms in pseudo-codes. CS1010 (AY2011/2 Semester 1)

  3. From reference book: C Programming for Engineering & Computer Science by Tan & D’Orazio’s Please read up on your own Chapter 1: Computers and Computing Fundamentals Source codes available on module website CS1010 (AY2011/2 Semester 1)

  4. 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. Computers as Information Processors (1/2) CS1010 (AY2011/2 Semester 1)

  5. Computer are Information Processors Raw data Computer system Processed information Computers as Information Processors (2/2) • Data units • Internal representation in machine • 1 bit (binary digit): 0 or 1 • 1 byte = 8 bits • Floating-point representation, etc. • Data types in programs • int, char, float, etc. CS1010 (AY2011/2 Semester 1)

  6. 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 (AY2011/2 Semester 1)

  7. 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 (AY2011/2 Semester 1)

  8. 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 (AY2011/2 Semester 1)

  9. 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 (AY2011/2 Semester 1)

  10. 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 (AY2011/2 Semester 1)

  11. Edit, Compile and Execute Source code produces Editor welcome.c eg: vim welcome.c Executable code produces Compiler a.out eg: gcc welcome.c Output Execute produces Hello, welcome to CS1010! eg: a.out CS1010 (AY2011/2 Semester 1)

  12. UNIX Workshop • Have you attended the UNIX workshop conducted on 1 and 2 August organised by the Computing Club, or on 11 and 12 August (last Thursday and Friday) by Aaron Tan? • If not, please go through the document “Getting Started with UNIX and CodeCrunch” on this website yourself after class: http://www.comp.nus.edu.sg/~cs1010/3_ca/labs.html CS1010 (AY2011/2 Semester 1)

  13. Logging into UNIX system (1/3) • 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 (AY2011/2 Semester 1)

  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 by next week’s lecture! CS1010 (AY2011/2 Semester 1)

  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 (AY2011/2 Semester 1)

  16. Problem Solving Process Determine problem features Analysis Rethink as appropriate Write algorithm Design Produce code Implementation Check for correctness and efficiency Testing • Refer also to Jumpstart to SoC on module website, “Misc…”, “For Freshmen”. CS1010 (AY2011/2 Semester 1)

  17. Algorithm Input Output 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. CS1010 (AY2011/2 Semester 1)

  18. 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 (AY2011/2 Semester 1)

  19. 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. CS1010 (AY2011/2 Semester 1)

  20. 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. A better version in next slide… CS1010 (AY2011/2 Semester 1)

  21. 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 Is there any error in this algorithm? CS1010 (AY2011/2 Semester 1)

  22. Find maximum and average of a list of numbers (3/3) 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 No Yes print max, ave max num num > max? No end CS1010 (AY2011/2 Semester 1)

  23. 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 (AY2011/2 Semester 1)

  24. 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 (AY2011/2 Semester 1)

  25. Control structures • Sequence • Branching (selection) • Loop (repetition) CS1010 (AY2011/2 Semester 1)

  26. A possible algorithm: enter values for num1, num2, num3 ave ( num1 + num2 + num3 ) / 3 print ave Another possible algorithm: enter values 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: Examples (1/4) • Example 1: Compute the average of three integers. CS1010 (AY2011/2 Semester 1)

  27. Variables used: num1 num2 final1 final2 Algorithm: Examples (2/4) • Example 2: Arrange two integers in increasing order (sort). Algorithm A: enter values for num1, num2 // Assign smaller number into final1, // larger number into 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 (AY2011/2 Semester 1)

  28. Variables used: num1 num2 temp Algorithm: Examples (3/4) • Example 2: Arrange two integers in increasing order (sort). Algorithm B: enter values for num1, num2 // Swap the values in the variables if necessary if (num2 < num1) then tempnum1 num1num2 num2temp // Display sorted integers print num1, num2 CS1010 (AY2011/2 Semester 1)

  29. Variables used: n count ans Algorithm: Examples (4/4) • Example 3: Find the sum of positive integers up to n (assuming that n is a positive integer). Algorithm: enter value 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 print ans CS1010 (AY2011/2 Semester 1)

  30. 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 (AY2011/2 Semester 1)

  31. 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 (AY2011/2 Semester 1)

  32. 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 (AY2011/2 Semester 1)

  33. Task: 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 (AY2011/2 Semester 1)

  34. 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 for the Coin Change problem: • Understanding the problem (if in doubt, ask questions!): 2-5 minutes • Writing the algorithm: 10-20 minutes • Testing the algorithm: 10-20 minutes • Writing the program: 10-20 minutes • Testing and debugging the program: 10 minutes to 1 hour • 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 (AY2011/2 Semester 1)

  35. 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 (AY2011/2 Semester 1)

  36. Summary for Part I • Part I’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 (AY2011/2 Semester 1)

  37. Part II: Overview of C Programming Objectives: • Able to write your first program with an editor • Able to execute your first program • Understand basic C constructs and arithmetic operations • Understand basic programming style References: • Chapter 2, Getting Started • Chapter 3, The Basics of C • Vim Quick Reference Card: http://tnerual.eriogerg.free.fr/vimqrc.pdf • Intro lab: http://www.comp.nus.edu.sg/~cs1010/labs/lab0/gettingStarted.html CS1010 (AY2011/2012 Semester 1)

  38. Part II: Outline • General: what is a program; various programming languages • Our first sample program • Demo: Getting your program to execute • Demo on ssh, basic UNIX commands, vim, gcc • Exercise #1 • Exercise #2 CS1010 (AY2011/2012 Semester 1)

  39. 1. General What is a “program”? A sequence of instructions that a computer can interpret and execute. The instructions follow the rules of the language chosen. There are many “types” of programming languages: A to Z http://en.wikipedia.org/wiki/List_of_programming_languages_by_category C: A general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Lab for use with the UNIX operating system. CS1010 (AY2011/2012 Semester 1)

  40. vim gcc execute program CS1010 (AY2011/2012 Semester 1)

  41. 2. Our First Program (1/4) Sample Run $ gcc Week2_MileToKm.c $ a.out Enter the distance in miles> 10.5 That equals 16.89 kilometers. CS1010 (AY2011/2012 Semester 1)

  42. 2. Our First Program (2/4) preprocessor directives main function heading { declarations executable statements } CS1010 (AY2011/2012 Semester 1) General form of a C program:

  43. 2. Our First Program (3/4) standard header file preprocessor directives constant reserved words comments variables standard identifiers special symbols punctuations CS1010 (AY2011/2012 Semester 1)

  44. 2. Our First Program (4/4) memory memory memory machine language Week2_MileToKm conversion program machine language Week2_MileToKm conversion program machine language Week2_MileToKm conversion program miles miles miles 10.5 10.5 ? At the beginning After user enters: 10.5to scanf("%f", &miles); After this line is executed: kms = KMS_PER_MILE * miles; kms kms kms 16.89 ? ? CS1010 (AY2011/2012 Semester 1)

  45. 3. Demo: Getting Program to Execute (1/2) CS1010 (AY2011/2012 Semester 1) • Log into sunfire • If this is your first time logging in • Run the setup script as shown in section 2.3 “Setting up your sunfire account” of http://www.comp.nus.edu.sg/~cs1010/labs/lab0/gettingStarted.html: ~cs1010/lab0/setupsource .bash_profile • Using basic UNIX commands • ls, rm, mv, cd, mkdir, chmod, cp, diff …

  46. 3. Demo: Getting Program to Execute (2/2) CS1010 (AY2011/2012 Semester 1) • vim: an editor with no need of a mouse • insertvscommand mode • i, <Esc>, dd, :w, ZZ, p, o • gcc: gccfilename.c –Wall –o filename • gcc does compile-assembly-linking all in one unless with –c option • Executing a program: filename • Exercise #1: • Use an editor to write: Week2_MileToKm.c (if you have copied this program from the CS1010 website, rename it or go to another subdirectory.) • Correct/Compile your program till it is free of (syntax) errors • Execute & test your program till it is free of (run-time & logic) errors

  47. 4. Exercise #2 (Fahrenheit to Celsius) (1/2) Enter temperature in Fahrenheit: 32.5 That equals 0.277778 Celsius. CS1010 (AY2011/2012 Semester 1) • Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius • Celsius = 5 / 9 * (Fahrenheit – 32) • Use the vim editor to write: Week2_FtoC.c • Correct/Compile your program till free of (syntax) error • Make sure your program is free of (run time, logic) error • Test on the following Fahrenheit degrees: • 32.5,0,-54.3,100 (and others of your choice) • Sample output:

  48. 4. Exercise #2 (Fahrenheit to Celsius) (2/2) • (Optional) Format the number of output digits to 2 decimal places • (Optional) Write another program to convert Celsius to Fahrenheit CS1010 (AY2011/2012 Semester 1) Do you get the correct answers? 

  49. Summary for Part II • Part II’s most important lessons • Worked in a UNIX system and used the vim editor • Learned about simple features and style in C • Written 2 programs to do arithmetic operations correctly CS1010 (AY2011/2012 Semester 1)

  50. Announcements/Things-to-do • Do Exercise #2 (if you have not completed it) • Discussion classes start in week 3 (next week) • Check out IVLE regularly for announcements and updates. • Read Chapter 2 Getting Started and Chapter 3 The Basics of C. • To prepare for next week: • Visit module website and IVLE • Read “CS1010 Handbook” • Read Chapter 5 CS1010 (AY2011/2 Semester 1)

More Related