P. 1
Week2.pptx

Week2.pptx

|Views: 8|Likes:
Published by Indigo Blue
asdf
asdf

More info:

Published by: Indigo Blue on Oct 19, 2013
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PPTX, PDF, TXT or read online from Scribd
See more
See less

10/19/2013

pdf

text

original

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

sg/~cs1010/

Week 2: Overview of C Programming
Objectives:  Able to create programs using the editor vim  Able to execute your first program  Understand basic C constructs, interactive input, output,
and arithmetic operations  Understand basic programming style

References:  Chapter 1, Lessons 1.6 – 1.9  Chapter 2 Variables, Arithmetic Expressions and Input/Output  Vim Quick Reference Card:
http://tnerual.eriogerg.free.fr/vimqrc.pdf  Getting Started with UNIX:
http://www.comp.nus.edu.sg/~cs1010/labs/2012/intro_lab/gettingStarted.html

CS1010 (AY2013/4 Semester 1)

Week2 - 2

Week 2: Outline
0. Algorithms (last week)
1. 2. 3. 4. General Our first sample program Errors: syntax, run-time, logic, and undetected errors Demo: Getting your program to execute
* Demo on ssh, basic UNIX commands * Exercise #1: Using vim and gcc

5. Exercise #2: Temperature Convert 6. Program structure as:
* Input: scanf()
* Compute: variables, data type, constants, precedence rules * Output: printf()

7. Exercise #3: Temperature Estimate 8. Style: naming, presentation, simplicity and efficiency 9. Common mistakes
This symbol indicates the focus of today’s lesson.
CS1010 (AY2013/4 Semester 1) Week2 - 3

ICI Nimrod Smalltalk. Pascal. Delphi IDL. RPG. Fortran.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. APL.1. Eiffel Java. Logo Q. VBA C.wikipedia. Vimscript. Ada F.4 . Ruby Winbatch D. F# K. Io.3 in book for more details) CS1010 (AY2013/4 Semester 1) Week2 . Scheme X++. JASS Oz Tcl. General Program: A sequence of instructions that a computer can interpret and execute. C#. Lisp. C++ Haskell M. Today Y. Python uniPaaS Basic G. XL E. There are many “types” of programming languages: A to Z A+. Z++ http://en. We will follow the ANSI C standard (see Lesson 1. The instructions follow the rules of the language chosen. Maple R.

c produces welcome.Edit.5 .c produces a. test. welcome to CS1010! Incorrect result? Test.out produces Hello. Compile and Execute Source code Editor eg: vim welcome.c Executable code Compiler eg: gcc welcome. and test! CS1010 (AY2013/4 Semester 1) Week2 .out Cannot compile? Output Execute eg: a.

scanf definitions */ #define KMS_PER_MILE 1. Our First Program (1/4) Week2_MileToKm.2f km. kms).c $ a.609 /* conversion constant */ int main(void) { float miles. &miles). } Sample Run $ gcc Week2_MileToKm. // Display the distance in kilometres printf("That equals %9. // Convert the distance to kilometres kms = KMS_PER_MILE * miles.\n".h> /* printf.c /* * Converts distance in miles to kilometres. return 0. kms.89 km. // input – distance in miles // output – distance in kilometres /* Get the distance in miles */ printf("Enter distance in miles: ").2. Week2 . */ #include <stdio. scanf("%f".5 That equals 16.6 CS1010 (AY2013/4 Semester 1) .out Enter distance in miles: 10.

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

&miles). } punctuations functions special symbols CS1010 (AY2013/4 Semester 1) Week2 . standard header file /* printf. // Convert the distance to kilometres kms = KMS_PER_MILE * miles. kms. kms). scanf definitions */ 1.2f km. scanf("%f". in miles to kilometres. return 0.\n".h> #define KMS_PER_MILE int main(void) { float miles. Our First Program (3/4) preprocessor directives /* * Converts distance */ #include <stdio.8 .2. // Display the distance in kilometres printf("That equals %9.609 /* conversion constant */ constant reserved words variables // input – distance in miles // output – distance in kilometres comments /* Get the distance in miles */ printf("Enter distance in miles: ").

&miles).2.9 .89 At the beginning Do not assume that uninitialised variables contain zero! (Very common mistake.c miles ? kms ? miles 10. Week2 .5 kms 16. After this line is executed: kms = KMS_PER_MILE * miles.c memory Executable code of Week2_MileToKm.5 kms ? miles 10.5 to scanf("%f". Our First Program (4/4)  What happens in the computer memory? memory Executable code of Week2_MileToKm.) CS1010 (AY2013/4 Semester 1) After user enters: 10.c memory Executable code of Week2_MileToKm.

10 CS1010 (AY2013/4 Semester 1) . unless otherwise stated  Outputs   Standard output stream (stdout) – default is monitor Use printf() function Week2 . Read inputs (scanf) 2. Print outputs (printf)  We will stick to interactive inputs   Standard input stream (stdin) – default is keyboard Use scanf() function  Assume input data are according to specification  No need to validate input data.Notes (1/2)  Basic steps of a program 1. Compute 3.

Notes (2/2)  Include <stdio.6 – 1. or CodeCrunch may mark your output as incorrect.\n". CS1010 (AY2013/4 Semester 1) Week2 .11 . printf("That equals %9.9  Read   Important! (CodeCrunch issue)  Make sure you have a newline character (\n) at the end of your last line of output.2f km.h> to use scanf() and printf() functions  Include the header file (for portability sake) even though some systems do not require you to do so Lessons 1. kms).

invalid expression. This process can be very time-consuming! CS1010 (AY2013/4 Semester 1) Week2 .12 . Errors  Syntax Errors (and warnings)    Program does not obey C construct /grammar such as invalid choice of identifier name.3. incomparable use of types for output We advise you to use gcc –Wall to compile your programs Program terminates unexpectedly due to illegal operation. Warning happens. missing semi-colon. etc. such as dividing a number by zero Program produces result as opposed to what is expected (wrong algorithm)  Run-time Errors   Logic Errors   Undetected Errors  Exist if we are not able to test all cases The process of correcting errors in programs is called debugging. for example.

nus. Demo: Getting Program to Execute (1/2)  Log into your UNIX account in sunfire  Follow last week‟s instructions (“Logging into UNIX system”)  If this is your first time logging in (that is.4 “Setting up your sunfire account” of http://www.13 .4.comp.edu.bash_profile  Go to the c subdirectory  This subdirectory should have been created if you have run the above setup step during the Intro Workshop CS1010 (AY2013/4 Semester 1) Week2 . you did not attend the Intro Workshop)  Run the setup script as shown in section 2.html: ~cs1010/workshop/setup source .sg/~cs1010/labs/2012/intro_lab/gettingStarted.

out or filename Exercise #1: Using vim and gcc    Use vim to create the program Week2_MileToKm. <Esc>.vimrc) is created and put into your home directory when you did the setup. o The configuration file (. :w.14 CS1010 (AY2013/4 Semester 1) . ZZ. p.4.c –Wall –o filename  Executing a program: a. Demo: Getting Program to Execute (2/2)  vim: an editor with no need of a mouse (setup . it controls how your vim looks and works gcc does compile-assembly-linking all in one go    Compile: gcc filename. dd.c Correct/compile your program till it is free of (syntax) errors Execute and test your program till it is free of (run-time and logic) errors Week2 .vimrc)    insert vs command mode Examples of commands: i.

5 That equals 0. logic) errors   Test on the following Fahrenheit degrees: 32.c Correct/compile your program till free of (syntax) errors Make sure your program is free of (run time. 100 (and others of your choice)  Sample output: Enter temperature in Fahrenheit: 32. CS1010 (AY2013/4 Semester 1) Week2 . Exercise #2 (Fahrenheit to Celsius) (1/2)  Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius  celsius = 5 / 9 * (fahrenheit – 32)    Use the vim editor to create Week2_FtoC.3. 0.5.5. -54.277778 Celsius.15 .

   (Optional) Format the number of output digits to 2 decimal places (Optional) Write another program to convert Celsius to Fahrenheit Week2 .16 CS1010 (AY2013/4 Semester 1) .5 That equals 0.5.277778 Celsius. Exercise #2 (Fahrenheit to Celsius) (2/2)  Do you get the correct answers? Enter temperature in Fahrenheit: 32.

or file input Compute: through arithmetic operations Output: through stdout (using printf). CS1010 (AY2013/4 Semester 1) Week2 .17 . Program Structure  A program has 3 main parts: (plus Preprocessor Directives: #include <stdio.6.h>)    Input : through stdin (using scanf). #include <math.h>. or file output We will learn file input/output later.

// cumulative average point printf("What are your age and CAP? "). &age. &age). Program Structure: Input/Output (1/2)  Input/output statements:    printf ( format string. and your CAP is %f\n". Week2_InputOutputV2.c double cap. Another version: Week2_InputOutput. “&age” refers to (address of) the memory point cell where the value of age is stored. printf ( format string ). printf("What is your CAP? "). “age” refers to value in the variable age. printf("You are %d years old. &cap). age. age. One version: int age. printf("You are %d years old. scanf("%d". cap). scanf("%lf". CS1010 (AY2013/4 Semester 1) Week2 . double cap. cap).18 . scanf("%d %lf". age 20 Address of variable „age‟ varies each time a program is run. scanf( format string.c int age. // cumulative average printf("What is your age? "). print list ). &cap).6. input list ). and your CAP is %f\n".

they are placeholders for values to be displayed or read Placeholder %c %d %f Variable Type char int float or double Function Use printf / scanf printf / scanf printf %f %lf %e    float double float or double scanf scanf printf (for scientific notation) Examples of format specifiers used in printf(): %5d: to display an integer in a width of 5. etc.3 (page 65) for sample displays Note: For scanf(). Week2 .19 CS1010 (AY2013/4 Semester 1) . decimal places. right justified %8. with 3 decimal places.6.3f: to display a real number (float or double) in a width of 8. just use the format specifier without indicating width. right justified   See Table 2. Program Structure: Input/Output (2/3)  %d and %lf are examples of format specifiers.

20 .4. It should be %% and not \% CS1010 (AY2013/4 Semester 1) Week2 .4 (pages 32 – 33) These are the more commonly used escape sequences: Escape sequence \n \t \" %% Meaning New line Horizontal tab Double quote Percent Result Subsequent output will appear on the next line Move to the next tab position on the current line Display a double quote " Display a percent character % Note the error in Table 1.6. Program Structure: Input/Output (3/3)     \n is an example of escape sequence Escape sequences are used in printf() function for certain special effects or to display certain characters properly See Table 1.

} CS1010 (AY2013/4 Semester 1) Week2 .21 .6. we have used one function: int main(void) main() function: where execution of program begins  A function body has two parts Declarations statements: tell compiler what type of memory cells needed  Executable statements: describes the processing on the memory cells  int main(void) { /* declaration statements */ /* executable statements */ return 0. Program Structure: Compute (1/10)  Computation is through function  So far.

hence value between -2. which is a letter.0E-4 (value is 0.14159 15.648 (-231) through +2.6.0015) 12e+5 or 12E+5 (value is 1200000.0)  float (and double)      char    individual character.147.0e-4 or 15.147. Program Structure: Compute (2/10)  Declaration Statements (2 parts: data type & identifier)  Part 1: Standard Data Types (data type: tells computer how to store a particular value in memory and what operations can be performed on the value. or a special symbol enclosed in a pair of single quotes 'A' 'z' '2' '9' '*' '?' ' ' '\n'  More data types later Week2 .)  int  32 bits.22 CS1010 (AY2013/4 Semester 1) . a digit.483.647 (231 – 1) an abstraction for real numbers (as it does not include all real numbers) 3.483.

6. printf. void. double. invalid: 1Letter. joe‟s valid: maxEntries. return e.23 . _X1234. scanf Avoid reserved words and standard identifiers Consist only of letters. and must not begin with a digit character Case-sensitive e.g. int. int. double.g. digit characters and underscores. TWO*FOUR. this_IS_a_long_name  Standard identifiers   User-defined identifiers     CS1010 (AY2013/4 Semester 1) Week2 . Program Structure: Compute (3/10)  Declaration Statements  Part 2: Identifier: name of a variable or function  Reserved words (or keywords)  e.g.

scanf) Assignment statements   stores a value or a computational result in a variable (Note: „=‟ is not equality.24 . Program Structure: Compute (4/10)  Executable Statements   I/O statements (e. CS1010 (AY2013/4 Semester 1) Week2 . printf.6. kms = KMS_PER_MILE * miles.g. but assignment) e.g.

b = c. b and a The above is equivalent to: a = (b = (c = 3 + 6)).g. // 9 assigned to variables c. with associativity from right to left:   CS1010 (AY2013/4 Semester 1) .  Note: Left side of an assignment statement is called lvalue – it must be assignable Examples of invalid assignment (result in compilation error “lvalue required as left operand of assignment”):    32 = a. a = b = c = 3 + 6. a + b = c. sum = sum + item. Program Structure: Compute (5/10) e.25  Assignment can be cascaded. which is also equivalent to: c = 3 + 6.6. a = b. Week2 .

// or z = (a = 12). Week2 . and 15 to a Side effects also apply to expressions involving other operators (eg: logical operators). but sometimes we do. besides assigning 12 to a Usually we don‟t make use of its side effect. (which gives 12) and assigns it to z Side effects have their use. Program Structure: Compute (6/10)  Side Effect:       An assignment statement does not just assigns. has the side effect of returning the value of 12. it also has the side effect of returning the value of its right-hand side expression Hence a = 12.26 CS1010 (AY2013/4 Semester 1) .6. // assign 10 to b. We will see more of this later. The above makes use of the side effect of the assignment statement a = 12. eg: z = a = 12. but avoid convoluted codes: a = 5 + (b = 10).

respecting parentheses rule. Program Structure: Compute (7/10)  Arithmetic operations  Binary Operators: +.c Week2 . subtraction are lower in precedence than multiplication. *. –. Try out Week2_ArithOps. and then associative rule (next page)  addition. n = 9 * 0. /.6. division. and then precedence rule. % (modulo or remainder)  Left Associative (from left to right)   46 / 15 / 2  3 / 2  1 19 % 7 % 3  5 % 3  2  Unary operators: +. and remainder int n.5. results in 4 being stored in n. –  Right Associative  x = – 23 p = +4 * 10  Execution from left to right.27  Truncated result if result can‟t be stored (the page after next)  CS1010 (AY2013/4 Semester 1) .

6.28 . Program Structure: Compute (8/10)  Arithmetic operators: Associativity & Precedence (Table 2. Page 76) CS1010 (AY2013/4 Semester 1) Week2 .6.

means = (float) (aa / 4).0. means Week2 . means  Type Casting  Use a cast operator to change the type of an expression  syntax: (type) expression int aa = float pp int nn float qq  CS1010 (AY2013/4 Semester 1) 6.0. means float p = 10/4. means float q = 10/4.8. means int r = -10/4.6.29 . means int n = 10/4. means = (int) ff / aa. = (float) aa / 4. Program Structure: Compute (9/10)  Mixed-Type Arithmetic Operations int m = 10/4.0. float ff = 15.

30 .6. Program Structure: Recall Exercise #2 (10/10)  CS1010 (AY2013/4 Semester 1) Week2 .

31 CS1010 (AY2013/4 Semester 1) . both values in integers. if the user entered 2 30 (2 hours 30 minutes).  Your program should prompt the user to enter how long it has been since the start of the power failure in hours and minutes.c that estimates the temperature in a freezer (in oC) given the elapsed time (hours) since a power failure. Week2 .7. Assume this temperature (T) is given by: 4t 2 T  20 t2 where t is the time since the power failure. Exercise #3 (temperature estimate) (1/2)  Write a program Week2_Freezer.5 hours before applying the above formula. Note that you need to convert the elapsed time into hours in real number (use type float). you need to convert this to 2.   For example.

63  How long does it take the freezer to get to zero degree? Which of the following is the closest answer? a) 3 hours b) 4 hours 10 minutes c) 6 hours 30 minutes d) 8 hours This is your take-home exercise. Enter hours and minutes since power failure: 2 45 Temperature in freezer = -13. Bring your program to class next week.7. Week2 . Follow the output format. This exercise is mounted on CodeCrunch as a practice exercise. Exercise #3 (temperature estimate) (2/2)  Refer to the sample run below.32   CS1010 (AY2013/4 Semester 1) .

discussion group. and spacing to emphasize block structure  Comments major code segments adequately:   Your name. Style  Identifier naming for variables and functions    User-defined identifiers: use lower-case with underscore or capitalise first character of every subsequent word (Eg: celsius.33  Refer to some C Style Guides on the module website  CS1010 (AY2013/4 Semester 1) . second_max. or /* block comment */ http://www.comp. // line comment. number. DAYS_IN_YEARS) Use names that are descriptive int main(void) { // statements }  Consistent indentation.8. program‟s purpose. secondMax) User-defined constants: use upper-case (Eg: KMS_PER_MILE.html Week2 . sum.edu.nus. Matric.sg/~cs1010/2_resources/online. etc.

 Forgetting & in a scanf() statement int x. b. x). Remove the file “core” (UNIX command: rm core) in your directory as it takes up a lot of space. a = b + 3. Common mistakes  Not initialising variables int a. int x = 0. // but what is the value of b?  Cannot assume that the initial value of b is zero! Unnecessary initialisation of variables int x = 0. scanf("%d". a “core dump” may happen.9. x = 531. &x).  Sometimes when your program crashes. Week2 . scanf("%d".34 CS1010 (AY2013/4 Semester 1) .

and assignment statements.Summary for Today    Using vim to edit programs. arithmetic operations.35 . Using gcc to compile C programs. Learn about basic structure of C programs:    Input (scanf) Compute Output (printf)  Learn about some data types. CS1010 (AY2013/4 Semester 1) Week2 .

c Read  Chapter 3 The Basics of C  Chapter 5 Functions Week2 .36 CS1010 (AY2013/4 Semester 1) .Announcements/Things-to-do   Do Exercise #3 Discussion classes start in week 3 (next week). Check out IVLE regularly for announcements and updates. Revise Chapters 1 and 2 To prepare for next week‟s lecture:      Bring your Exercise #3 program Week2_Freezer.

37 .Next Week  On how to design a “bigger” program from problem definition  Lots about functions. besides the main function Determine problem features Analysis Rethink as appropriate Write algorithm Design Produce code Implementation Check for correctness and efficiency CS1010 (AY2013/4 Semester 1) Testing Week2 .

End of File .

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->