1 / 41

Beginning C for Engineers Fall 2005

Beginning C for Engineers Fall 2005. Instructor: Bettina Schimanski TAs: Gabe Mulley & Joel Dever Website: www.cs.rpi.edu/~schimb/beginC2005 Lecture 1 – Section 2 (8/31/05) Section 4 (9/1/05). Overview. Course Goals Introduction Unix and the History of C First C Program

audi
Télécharger la présentation

Beginning C for Engineers Fall 2005

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. Beginning C for EngineersFall 2005 Instructor: Bettina Schimanski TAs: Gabe Mulley & Joel Dever Website: www.cs.rpi.edu/~schimb/beginC2005 Lecture 1 – Section 2 (8/31/05) Section 4 (9/1/05)

  2. Overview • Course Goals • Introduction • Unix and the History of C • First C Program • Data Types and expressions • I/O Beginning C for Engineers Fall 2005 - Lecture 1

  3. Course Goals • Introduce general concepts of programming • Begin to think like a programmer • Start programming in C • Why is this important? • To understand basic computer concepts • To appreciate structured programming • Will serve as a basis for any future programming you do • Needed for the Laboratory Introduction to Embedded Control (LITEC) course – ENGR 2350 Beginning C for Engineers Fall 2005 - Lecture 1

  4. What is programming? • Given a well-defined problem: • Find an algorithm to solve a problem • Express that algorithm in a way that the computer can execute it • An algorithm is a sequence of instructions to solve a problem such that: • Each instruction is unambiguous and is something the computer can do • After an instruction is finished there is no ambiguity about which instruction is to be executed next • Execution finishes in a finite number of steps • The description of the algorithm is finite Beginning C for Engineers Fall 2005 - Lecture 1

  5. C Programming Language • Evolved from BCPL (1967) and B (1969) • By Dennis Ritchie at Bell Labs • By the late 1970s it was widely used • Standardized in 1989 in the US through the American National Standards Institute (ANSI) and worldwide through International Standards Organization (ISO) • C++ is a superset of C Beginning C for Engineers Fall 2005 - Lecture 1

  6. C Standard Library • C programs consist of many functions • C Standard Library - collection of existing functions • Programming in C is a combination of: • Creating your own functions • Using C Standard Library functions Beginning C for Engineers Fall 2005 - Lecture 1

  7. C Portability • C is hardware-independent • Applications in C can run with little or no modifications on a wide range of computer systems • Use ANSI standard library functions instead of your own equivalent Beginning C for Engineers Fall 2005 - Lecture 1

  8. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Architecture of a Computer • I/O devices • Input • Output • CPU • ALU • Main Memory • Secondary Storage Beginning C for Engineers Fall 2005 - Lecture 1

  9. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage • Communications with the outside world • Input devices: • keyboard • mouse • joystick • scanner • microphone • Output devices: • screen • printer • computer speakers • networks I/O Devices Beginning C for Engineers Fall 2005 - Lecture 1

  10. Central Processing Unit (CPU) Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage • “Administrative” section of the computer – supervises operations: controls I/O and ALU • Has 2 components to execute program instructions • Arithmetic/Logic Unit performs arithmetic operations, and makes logical comparisons • Control Unit controls the order in which your program instructions are executed • Uses one or more registers as scratch space for storing numbers between instructions • A typical CPU today can execute millions of arithmetic operations in a second Beginning C for Engineers Fall 2005 - Lecture 1

  11. Central Processing Unit (CPU) Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Beginning C for Engineers Fall 2005 - Lecture 1

  12. Central Processing Unit (CPU) Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Many computers now have multiple CPUs (multiprocessors) and can therefore perform many operations at a time Beginning C for Engineers Fall 2005 - Lecture 1

  13. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage • Sometimes called random access memory (RAM). • Stores the numbers (data) that a program uses when it runs on the computer. • Contains millions of circuits which are either off or on (0 or 1)  Binary • Also stores the instructions of the program that is running on the computer. • Divided into fixed size units of memory called words. • each word stores one number • each word has its own address Main Memory Data Program Instructions Beginning C for Engineers Fall 2005 - Lecture 1

  14. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Main Memory Data Program Instructions Beginning C for Engineers Fall 2005 - Lecture 1

  15. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Secondary Storage • Permanent storage used to save data and programs when they are not running on the computer. • Data and programs are organized into varying size units called files. • Files are organized into directories that can contain subdirectories. • Secondary storage is cheaper per Megabyte than main memory, but access to data is muchslower Beginning C for Engineers Fall 2005 - Lecture 1

  16. Computer I/O Devices RAM (memory) Central Processing Unit (CPU) Registers Secondary Storage Secondary Storage Beginning C for Engineers Fall 2005 - Lecture 1

  17. The Programming Process • Use an editor (such as Emacs, Notepad, Vi, etc.) to create a program file (source file) • contains the text of the program written in some programming language (like C) • Use a preprocessor to include the contents of other files • Use a compiler to convert the source file into a machine code file (object file) • convert from “English” to binary with machine operations • Use a linker to convert the object file into an executable file. • include other machine code that the program requires • Run the executable file Beginning C for Engineers Fall 2005 - Lecture 1

  18. Creating a C Program • A C program is a set of functions that collectively solve a given problem. • each function is a sequence of C statements (instructions) • execution always begins with a function named “main” • one function calls another function to get it to execute its statements • The C statements in a function are executed one after the other in sequential order as written. Each C statement is ended by a semi-colon. Beginning C for Engineers Fall 2005 - Lecture 1

  19. First C Program /* Bettina Schimanski Hello World Program prog01a.c August 31, 2005 */ #include <stdio.h> int main () { printf(“Hello, World!\n”); return 0; } • Anything between /* and */ is a comment intended to improve the readability of the program. • #include is used to tell the compiler and linker what library resources the program uses. • the <stdio.h> library defines everything you need to display messages on the screen • This program contains one function named “main”. • Notice where semi-colons are placed. • The program outputs (prints to the screen) the words Hello, World! Beginning C for Engineers Fall 2005 - Lecture 1

  20. Displaying Messages On The Screen: Using printf • To display a message on the computer screen use the printf statement. • The back slash “\” indicates an escape sequence. This means take the alternate meaning of whatever immediately follows it. • \n means to start a new line • \t is a tab • \” is a quote • \a is an audible alert (bell) • Text strings must always be surrounded by double quotes. printf(“Hello, World\n”); Beginning C for Engineers Fall 2005 - Lecture 1

  21. More Examples printf(“Hello\nWorld!\n”); printf(“\tFirst part of long message. ”); printf(“Second part of long message.\n”); printf(“\”Hello\” World!”\n”); Hello World! First part of long message. Second part of long message. “Hello” World!” Beginning C for Engineers Fall 2005 - Lecture 1

  22. Defining a C Function • A C function has the following form: • The name of this function is “main”. • The word “int” means that this function returns an integer number. • using 0 to indicate that the program ran correctly. • this is what the return statement does at the end of the function • The braces define the beginning and the end of the function. • The first line of the function is called the function header. int main ( ) { sequence of statements separated by semicolons return 0; } Beginning C for Engineers Fall 2005 - Lecture 1

  23. First Lab! • Go to http://www.cs.rpi.edu/~schimb/beginC2005 • Click on Lectures & Labs and go to Lab 1 • Do just Part 1 Beginning C for Engineers Fall 2005 - Lecture 1

  24. Standard Data Types in C • A data type tells what type of data is storedin a given memory location. Standard C data types are broken into the following types: • Integral Types • represent whole numbers and their negatives • declared as int,short, orlong • Floating Types • represent real numbers with a decimal point • declared as float, or double • Character Types • represent single characters • declared as char Beginning C for Engineers Fall 2005 - Lecture 1

  25. C Variables int x; float sum, product; • Variables in C store data in memory so that the data can be accessed throughout the execution of a program • A variable stores data corresponding to a specific type. • Each variable that a C program uses must be declared at the beginning of the function before it can be used. • specify the type of the variable • numeric types: int short long float double • character type: char • specify a name for the variable • any previously unused C identifier can be used (with some more exceptions discussed later) Beginning C for Engineers Fall 2005 - Lecture 1

  26. What Does a Variable Declaration Do? int apartmentNumber; float tax_rate_Y2K; char middleInitial; A declaration tells the compiler to allocate enough memoryto hold a value of this data type, and to associate the identifierwith this location. 4 bytes for taxRateY2K 1 byte for middleInitial Beginning C for Engineers Fall 2005 - Lecture 1

  27. Variable and function Names In C • Some reserved words in C: • Variables and function names in C are called identifiers. • identifiers are used for many other things as well • Rules for constructing valid identifiers in C: • can contain letters (upper and lower case), digits, and the underscore ( _ ) character • cannot start with a digit • cannot be a reserved word • can be at most 256 characters long, though some compilers only look at first 32 characters • are case sensitive break case char const continue default do double else enum float for goto if int long return short signed static struct switch typedef union unsigned void while Beginning C for Engineers Fall 2005 - Lecture 1

  28. Identifiers • VALID apartment_number tax_rate_Y2K PrintHeading ageOfHorse_ • NOT VALID (Why?) apartment# 2000TaxRate Age-Of-Catday of week • ** Using meaningful variable names is a good programming practice Beginning C for Engineers Fall 2005 - Lecture 1

  29. Giving a Value to a Variable You can assign (give) a value to a variable by using the assignment operator = VARIABLE DECLARATIONS char middleInitial ; char letter ; int apartmentNumber; VALID ASSIGNMENT STATEMENTS middleInitial = ‘K’ ; letter = middleInitial ; apartmentNumber = 8 ; Beginning C for Engineers Fall 2005 - Lecture 1

  30. Assignment Statement • An assignment statement is used to put a value into a variable. • The previous value is replaced • Syntax: <variable> = <expression>; • <variable> is any declared variable in the program • <expression> is anything that produces a value of the appropriate type (more on this later) • first, the expression on right is evaluated. • then the resulting value is stored in the memory location of variable on left. Beginning C for Engineers Fall 2005 - Lecture 1

  31. Examples • Examples: count = 10; count = count + 1; area = 3.14 * radius * radius; • NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for expression and variable Beginning C for Engineers Fall 2005 - Lecture 1

  32. Arithmetic Expressions With Integers (int, long) • Operators: result is always an integer Symbol Name Example Value (x = 10, y=3) + addition x + y 13 – subtraction x – y 7 * multiplication x * y 30 / quotient x / y 3 % remainder x % y 1 – unary minus –x -10 + unary plus +x 10 Beginning C for Engineers Fall 2005 - Lecture 1

  33. Arithmetic Expressions Continued… • You can string the operators together to build longer expressions. • use parentheses to specify order of operations • precedence (after sub-expressions in parentheses): • first: unary plus and minus from right to left • second: *and / and % from left to right • third: + and – from left to right Beginning C for Engineers Fall 2005 - Lecture 1

  34. Arithmetic Expression Example int y = 2; int z; z = -y * 3 * (4 + 5) % 10 + - -3; -2 * 3 * 9 % 10 + - -3 -2 * 3 * 9 % 10 + 3 -6 * 9 % 10 + 3 -54 % 10 + 3 -4 + 3 -1 Beginning C for Engineers Fall 2005 - Lecture 1

  35. Arithmetic Expressions With Reals (float, double) • Arithmetic expressions with real numbers (numbers with decimal points) work the same way as with integers, with a few exceptions: • there is no remainder operator (“%”) • the “/” operator means “divide” (vs quotient), computing the answer to many decimal places • the result is a real value rather than an integer value • Important: Real values are approximate and may contain errors in the last few digits. • about 7 digits of accuracy for type float • about 14 digits of accuracy for type double Beginning C for Engineers Fall 2005 - Lecture 1

  36. Mixed Mode Arithmetic Expressions • Arithmetic expressions: both integers and floats can get tricky. • if both operands are integers, integer arithmetic is used • if either operand is a float, float arithmetic is used • an integer operand is converted to float for the operation • Examples: int a, x; x = 3.59; /* x gets the value 3 (no rounding) */ float y = 3; /* y gets the value 3.0 */ a = 12; /* a gets the value 12 */ float avg = (a + x) / 2; /* avg gets the value 7.0 … UH OH!!! */ Beginning C for Engineers Fall 2005 - Lecture 1

  37. Printing variables and constants to the screen with printf • Use the following conversion specifications: %d for an integer %ld for a long integer %c for a character %f for a float %f for a double Example: Output: int sum = 5; float avg = 12.2; char ch = ‘A’; printf(“The sum is %d\n”, sum); The sum is 5 printf(“avg = %f”\n”, avg); avg = 12.2 prinf(“ch = %c\n”, ch); ch = A printf(“%d, %f, %c\n”, sum, avg, ch); 5, 12.2, A printf(“%d\n”, 5); 5 Note: see p. 153 in your textbook for a complete list of all data types Beginning C for Engineers Fall 2005 - Lecture 1

  38. Reading data from the keyboard with scanf • Used to assign a value typed on the keyboard to a variable. • Used similarly to printf. You must use the following conversion specifications: Data Type printf converstion spec. scanf conversion spec. int %d %d long %ld %ld float %f %f double %f %lf char %c %c character string %s %s • The user must type a value followed by the Enter Key. • Ex: scanf(“%d”, &num); Beginning C for Engineers Fall 2005 - Lecture 1

  39. Example: Program to find the average of two numbers #include <stdio.h> int main () { int num1, num2; float avg; /* get two inputs */ printf( "Enter the first integer:”); scanf(“%d”, &num1); printf(“Enter the second integer:”); scanf(“%d”, &num2); /* compute and print the avg */ avg = (num1 + num2) / 2.0; printf(“The average is %f\n”, avg); return 0; } • Note that you can declare more than one variable per line. • We divide by 2.0 instead of 2 so that the right hand side is a float (i.e. no truncation takes place) • scanf is used similarly to printf, except that you need to put an ampersand (&) before the variable name • The first argument of the scanf function is the conversion specifier(s) in quotes, then the variable name(s) Beginning C for Engineers Fall 2005 - Lecture 1

  40. Finish Lab 1 • Go to http://www.cs.rpi.edu/~schimb/beginC2005 • Click on Lectures & Labs and go to Lab 1 • Do Part 2 Beginning C for Engineers Fall 2005 - Lecture 1

  41. Homework • Read Chapters 1,2 and 9 • Due at the beginning of next class: • HW 1 • Academic Integrity Statement • FYI: Info on Cygwin, Putty, SecureCRT, and Emacs are on the website Beginning C for Engineers Fall 2005 - Lecture 1

More Related