Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C Programming.

Similar presentations


Presentation on theme: "Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C Programming."— Presentation transcript:

1 Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C Programming

2 Review of Unit 1 Unit 1: Review

3 A Computer System is … Hardware: Central processing unit (CPU) Main memory (RAM, ROM) Secondary memory (Hard disk, CD, DVD, flash drive, etc) Input devices Output devices Network interface Power supply Software: Firmware Operating system Application programs

4 What is a Software Program? A set of instructions Performs a specific task Required to make the hardware do something The hardware runs or executes it Must be in main memory (RAM or ROM) Is written in machine language (specific to a CPU) Consists of binary 1s and 0s

5 What Programs Have in Common Programs process information: Information is stored in the form of binary data Different types of information use different data types Programs acquire input data Programs produce output data Programs are implementations of algorithms: Algorithms are precise solutions to problems Programs are written in programming languages: May be compiled (translated) to machine language May be compiled to intermediate form and then interpreted

6 Embedded Systems Found everywhere as part of electronic devices Examples: Watches, calculators, appliances, irrigation and lighting systems, copiers, traffic lights, MP3 players Pre-programmed computer Dedicated to a few functions inside a device Often must be real-time (respond immediately to events) Non-stop computing (continuously functioning) Traditionally viewed as non-reprogrammable Reprogrammability is becoming commonplace Therefore, programming is essential to electronics students!

7 Creating a Program Use problem solving skills Create an algorithm Implement the algorithm in a programming language Understand the programming model Use specialized tools Use software engineering methodology

8 Use Problem-Solving Process Heuristics (strategies) for successful problem solving Five-step process (from Strategies for Creative Problem Solving, Fogler et al.): 1. Define the problem 2. Generate possible solutions 3. Evaluate and decide on a solution 4. Implement the solution 5. Evaluate the solution

9 Develop Problem-Solving Skills A good programmer is an effective problem solver Has a belief that problems can be solved through analysis Develops a high level of problem-solving skills: Active – Makes sketches, draws figures, asks questions Methodical – Keeps track of progress in solving the problem Detail-oriented Takes great care to understand facts and relationships Checks and re-checks for accuracy

10 Create an Algorithm Develop an algorithm before writing a program Use precise statements Based in mathematics and logic Clear and concrete language Define a step-by-step process Goal is solution to a problem

11 Software Development Method 1. Specify the problem requirements 2. Analyze the problem 3. Design the algorithm to solve the problem 4. Implement the algorithm as a program 5. Test and verify the completed program 6. Maintain and update the program

12 Analyzing the Problem Requires identifying the … Inputs – the data available to work with Outputs – the desired results Including the format of the output Additional requirements Constraints

13 Producing the Algorithm List of steps from beginning to end Begin at step 1, have a specific step to end Dont try to get every detail at first Use top-down design: Break the problem into subproblems Solve each subproblem individually Similar to outlining a written paper Use pseudo-code combined with flowcharting Desk-check the algorithm

14 Begin and End Shapes These shapes are used to begin and end a flowchart The beginning shape has the algorithm name as its label The end shape contains the word End

15 Rectangle Shape – Actions Rectangle has one entry and one exit The text in the rectangle is pseudo-code corresponding to one step in the algorithm

16 Diamond Shape – Decision Point One entry, two exits (one for yes, the other for no) Contains one question, with yes/no answer

17 Selection Shape Selection is an extension of the decision point Instead of a question, the diamond contains a value The value selects which branch to take One other branch is used for all other values that dont have a branch

18 Connector Shape – On-page Use for a connection on same page Shape shows connection from one point to another Left shape can be used multiple times Right shape, used once, shows the destination of connection

19 Connector Shape – Off-page Use for a flowchart larger than one page Shape shows connection from one page to another Left shape can be used multiple times Right shape, used once, shows the destination of connection Visio automatically creates a new page when this shape used

20 Introducing the C Language Unit 2: Introduction to the C Programming Language

21 Origin and History of C Lineage: BCPL (Martin Richards, Univ of Cambridge, 1966) B programming language (Ken Thompson et al., Bell Labs, 1969) Creation: Dennis Ritchie of AT&T Bell Labs Supported development of UNIX Peculiarities: Terse language – author of C didnt like typing Widespread use led to many variations in 1980s Syntax and idioms can be frustrating to learn

22 Standardization By mid-to-late 1980s: Many differing implementations on different computers Incompatible extensions Incompatibilities in "standard" libraries American National Standards Institute (ANSI) – 1989: Created a standard, now called C89 International Organization for Standardization (ISO) – 1990: Adopted ANSI standard, now called C90 (same as C89) C99 - Revision published in 1999 (slow adoption, Pelles C is C99) C1X - New revision underway Ensures that all standard C implementations are compatible: Defines the meaning and extent of compatibility

23 C Has Many Successors Subsequent creation of many C-like derivative languages: Embedded C (ISO C Standards Committee, 2008) C++ (Object-oriented, Bjarne Stroustrup, Bell Labs) C# for.NET (Object-oriented, Anders Hjelsberg, Microsoft) Java and derivatives (Sun Microsystems) Perl (structurally similar to C) Ruby … and many other less popular languages

24 C is a Procedural Language C is a high-level procedural language: In C, a procedure is called a function Program divided into a number of functions Each function consists of steps called statements Statements may use other functions Matches top-down design: Sub-problem solved with a function Function implements an algorithm Functions operate on data in the form of: Constants - values that do not change, such as 12, 2.5, and bacon Variables - named locations in memory

25 The Hello, World! Program Flowchart for the traditional first C program: Lets see what it takes to implement this in C.

26 The Hello, World! Program in C #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

27 Structure of a C Program Unit 2: Introduction to the C Programming Language

28 Each Program has a main() This program has a function named main() The compiler looks for main() as the starting point The loader starts the program at main() The function body is inside the { and } (braces) #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

29 Statements Function body has one or more statements (this one has 2) Each statement is a step, like a rectangle on a flowchart All statements must end with a semicolon (shown in red) (You may, at first, feel frustrated by the semicolons) #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

30 Use of a Library Function This main() uses another function named printf() The printf() function is in the Standard I/O (stdio) library The standard libraries are supplied with the C compiler The #include line allows us to use the stdio.h library header #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

31 A Function's return Statement The caller of a function is that program which started it running Functions can return a value back to the caller The main() function always returns zero ( 0 ) to the OS The word int indicates the type of value that main() will return #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

32 Constant Values A C program can contain various constant values The text inside the double-quote characters is called a string constant The zero character, 0, is called an integer constant #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

33 Miscellaneous A comment starts with /* and ends with */ The entire comment is ignored by the compiler Comments are included in programs to aid in human understanding The word void in main() will be explained in a later class #include /* Our first C program */ int main(void) { printf("Hello world!\n"); return (0); }

34 Algorithm to Convert miles to km 1. Output Convert miles to kilometers 2. Output Please enter the distance in miles 3. Input dist_in_miles 4. Convert dist_in_miles to kilometers a) Multiply dist_in_miles by b) Put the result in dist_in_kms 5. Output The distance in kilometers is 6. Output dist_in_kms 7. End This algorithm was presented in Unit 1

35 Program to Convert miles to km #include int main(void) { double dist_in_miles, dist_in_kms; printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

36 The Statements Match the Algorithm Each step in the algorithm becomes a statement: #include int main(void) { double dist_in_miles, dist_in_kms; printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

37 Variables Must be Declared Variables used in the function must be declared before use: #include int main(void) { double dist_in_miles, dist_in_kms; /* Declaration */ printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

38 C Syntax Requires Exact Punctuation Parentheses, brackets, and braces always are in matched pairs Commas are used to separate items in a list A semicolon must end each statement #include int main(void) { double dist_in_miles, dist_in_kms; printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

39 Some Special Words are Reserved Reserved words have special use and meaning Functions cannot use reserved words as their names Variables cannot use reserved words as their names #include int main(void) { double dist_in_miles, dist_in_kms; printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

40 C Reserved Words The C language has 32 reserved words: autodoubleintstruct breakelselongswitch caseenumregistertypedef charexternreturnunion constfloatshortunsigned continueforsignedvoid defaultgotosizeofvolatile doifstaticwhile This list is also in Appendix E of the textbook

41 The printf() Function The printf() function is in library It creates formatted output for the console display Can output a string of characters printf("Hello World!\n"); Can output numeric data from constants or variables printf("%f", 12.5); printf("%f", dist_in_kms); The % character and the character(s) that follow are called conversion specifiers (Hanly book, et al, use term format placeholders).

42 The scanf() Function The scanf() function is in library It performs formatted input from the console keyboard Can input numeric data into variables scanf("%lf", &dist_in_miles); The '&' character is required to designate an input variable The '%' character and the letter(s) that follow are conversion specifiers (or format placeholders). We will come back to printf() and scanf() later

43 Variables and Data Types Unit 2: Introduction to the C Programming Language

44 Data Resides in Variables Variables must be declared to the compiler double dist_in_miles, dist_in_kms; The compiler manages size and location in main memory Programmer refers only to the variable's name Name should be descriptive of data in variable Each variable also has a data type The word that begins the declaration is the data type, for example, "double" as shown above

45 Variables Placed in Main Memory by Compiler

46 Variable Name Rules ANSI C Rules: Only letters, digits, and underscores (_ shift-minus) Cannot begin with a digit Uppercase is different than lowercase Cannot be a reserved word Tips: Don't use a name found in a C standard library Use a standard coding style (we'll talk more about this next unit)

47 Data Types in C int - An integer, positive or negative (signed) whole number float - A signed number with fraction in scientific notation E E-6 double - Like float with twice the precision (Once used sparingly as inefficient, now is the norm) char - A single ASCII character '.''r''E''4'' ''?'

48 Typical Usage of Numeric Data Types double Money Measurements of physical quantities (distance, voltage, current) Very large and very small numbers int Counters Index (position in a list) Settings, positions of dials and controls Digital and binary values

49 Advanced Data Types An int is typically 32 bits signed two's complement binary Its range is to signed or unsigned Can combine with int signed int - same as an int unsigned int - positive numbers only 0 to short or long Can combine with int and unsigned int short int - 16-bit binary to unsigned short int - 16-bit binary 0 to long int - on some machines can be a 64-bit integer

50 String Constants Unit 2: Introduction to the C Programming Language

51 String Constants Defined A string constant is zero or more characters (A string constant can be empty) Each character takes one byte in memory (An extra zero byte is used in memory at the end of a string) Each character is encoded using the ASCII code A string constant must begin and end with a double-quote (The quote characters are not stored in memory)

52 String Constants - Examples "Hello World" "Hello" and "Hello " are different "134.5" is not a number, it's a string is a string containing punctuation characters "" is the empty string " " is a string consisting of a space; it's not empty "AF" and "af" are different - case sensitive

53 String Escape Sequences Put special characters in a string or character constant Sequence of characters, starting with backslash \ Put quote or double-quote in a string or character constant "\"Hi!\", we said." Single string of 15 characters Put a backslash in a string or character constant "\\" A string with one backslash character Put special codes in a string or character constant "\n" Makes console output start a new line "\t" Outputs a tab character '\g' Make a "beep" noise from the speaker

54 More on printf( ) and scanf( ) Unit 2: Introduction to the C Programming Language

55 The printf( ) Function Function accepts one or more inputs (called arguments) First argument is a string (called format string) Format string can contain: Text One or more format placeholders, mixed in with text The official name of a format placeholder is a conversion specifier Format placeholders begin with a % character Placeholders are only understood by printf, in its 1 st argument The formatted text prints on the console screen

56 Conversion Specifiers for printf( ) Formatting an int: %dFormat as decimal integer27 %bFormat as binary integer11011 %xFormat as hexadecimal integer1b %XFormat as hex integer using uppercase1B Formatting a float or double: %fFormat as decimal fraction0.125 %eFormat as scientific notation1.25e-1 %ESame as %e but with capital E1.25E-1 Formatting a character: %cFormat as a single characterx Formatting a string: %sFormat as a stringxyzzy For a '%' character - must use %

57 Examples of printf( ) 1 of 3 Assume the following variables and values: int pebble_count; /* There are 14 pebbles */ Example: printf("There are %d pebbles\n", pebble_count); Output: There are 14 pebbles

58 Examples of printf( ) 2 of 3 Assume the following variables and values: double radius; /* The radius is 1.5 */ Example: printf("The radius is %f\n", radius); Output: The radius is

59 Examples of printf( ) 3 of 3 Assume the following variables and values: double gas_cost; /* The value is */ double pct_gas; /* The value is 17.5 */ Example: printf("%s cost $ %f, %f % of your budget.\n," "Gas", gas_cost, pct_gas); Output: Gas cost $ , % of your budget.

60 The scanf( ) function Function accepts one or more inputs (called arguments) First argument is a string (called format string) Format string can contain: Text One or more format placeholders, mixed in with text The official name of a format placeholder is a conversion specifier Format placeholders begin with a % character Placeholders are only understood by scanf, in its 1 st argument Remaining arguments must be variables Each variable preceded with & character

61 Conversion Specifiers for scanf( ) For inputting an int: %dInput as decimal integer %bInput as binary integer %xInput as hexadecimal integer For inputting a float: %fInput a float For inputting a double: %lfInput a double (The lf means "long float", i.e. double) For inputting a char: %cInput a single character Codes for inputting a string: %sInput a string These codes must match the data type of the variable

62 Examples of scanf( ) 1 of 2 Assume the following variables: double radius; Example: printf("Enter a radius: ");/* Note no newline */ scanf("%lf", &radius);

63 Examples of scanf( ) 2 of 2 Assume the following variables: int pebbles; Example: printf("How many pebbles? "); /* Note no newline */ scanf("%d", &pebbles);

64 Human Factors Note Technique for asking for short-answer input at the console: Be clear in what data is requested Provide information about the type of data needed Output a prompt (before scanf) explaining what to enter: printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); Make sure input position is after prompt, with a separator: There is no newline character at end of the printf string There is a space at end of the printf string


Download ppt "Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C Programming."

Similar presentations


Ads by Google