Upload
barrie-french
View
219
Download
0
Tags:
Embed Size (px)
Citation preview
Beginning C for EngineersFall 2005
Instructor: Bettina SchimanskiTAs: Gabe Mulley & Joel Dever
Website: www.cs.rpi.edu/~schimb/beginC2005
Lecture 1 – Section 2 (8/31/05)Section 4 (9/1/05)
Beginning C for Engineers Fall 2005 - Lecture 1
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
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
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
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
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 functionsUsing C Standard Library functions
Beginning C for Engineers Fall 2005 - Lecture 1
C Portability
C is hardware-independentApplications 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
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Architecture of a Computer
I/O devices Input Output
CPU ALU Main Memory Secondary Storage
Beginning C for Engineers Fall 2005 - Lecture 1
I/O Devices Communications with the
outside world Input devices:
keyboard mouse joystick scanner microphone
Output devices: screen printer computer speakers networks
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Beginning C for Engineers Fall 2005 - Lecture 1
“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
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Central Processing Unit (CPU)
Beginning C for Engineers Fall 2005 - Lecture 1
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Central Processing Unit (CPU)
Beginning C for Engineers Fall 2005 - Lecture 1
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Central Processing Unit (CPU)
Many computers now have multiple CPUs (multiprocessors) and can therefore perform many operations at a time
Beginning C for Engineers Fall 2005 - Lecture 1
Main Memory
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
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Data
Program
Instructions
Beginning C for Engineers Fall 2005 - Lecture 1
Main Memory
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Data
Program
Instructions
Beginning C for Engineers Fall 2005 - Lecture 1
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 much slower
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Beginning C for Engineers Fall 2005 - Lecture 1
Secondary Storage
RAM (memory)
I/O Devices
Central ProcessingUnit (CPU)
Secondary Storage
Registers
Computer
Beginning C for Engineers Fall 2005 - Lecture 1
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
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
First C Program 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!
/* Bettina Schimanski Hello World Program
prog01a.cAugust 31, 2005
*/
#include <stdio.h>
int main (){
printf(“Hello, World!\n”);
return 0;
}
Beginning C for Engineers Fall 2005 - Lecture 1
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
More Examplesprintf(“Hello\nWorld!\n”);printf(“\tFirst part of long message. ”);printf(“Second part of long message.\n”);printf(“\”Hello\” World!”\n”);
HelloWorld!
First part of long message. Second part of long message.“Hello” World!”
Beginning C for Engineers Fall 2005 - Lecture 1
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
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
Standard Data Types in C A data type tells what type of data is stored in 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, or long
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
C Variables
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)
int x;
float sum, product;
Beginning C for Engineers Fall 2005 - Lecture 1
What Does a Variable Declaration Do?
A declaration tells the compiler to allocate enough memory to hold a value of this data type, and to associate the identifier with this location.
int apartmentNumber;float tax_rate_Y2K;char middleInitial;
4 bytes for taxRateY2K 1 byte for middleInitial
Beginning C for Engineers Fall 2005 - Lecture 1
Variable and function Names In C Some reserved
words in C:break case char const continue default do double else enum floatfor gotoif
int long returnshortsignedstaticstructswitchtypedefunionunsignedvoidwhile
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
Beginning C for Engineers Fall 2005 - Lecture 1
Identifiers VALID
apartment_number tax_rate_Y2K
PrintHeading ageOfHorse_
NOT VALID (Why?)
apartment# 2000TaxRate Age-Of-Cat day of week
** Using meaningful variable names is a good programming practice
Beginning C for Engineers Fall 2005 - Lecture 1
Giving a Value to a Variable
You can assign (give) a value to a variable by using the assignment operator =
VARIABLE DECLARATIONSchar middleInitial ;char letter ;int apartmentNumber;
VALID ASSIGNMENT STATEMENTSmiddleInitial = ‘K’ ;letter = middleInitial ;apartmentNumber = 8 ;
Beginning C for Engineers Fall 2005 - Lecture 1
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
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
Examples
Beginning C for Engineers Fall 2005 - Lecture 1
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
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
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
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
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
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 5printf(“avg = %f”\n”, avg); avg = 12.2prinf(“ch = %c\n”, ch); ch = Aprintf(“%d, %f, %c\n”, sum, avg, ch); 5, 12.2, Aprintf(“%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
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 %dlong %ld %ldfloat %f %fdouble %f %lfchar %c %ccharacter 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
Example: Program to find the average of two numbers
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)
#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;}
Beginning C for Engineers Fall 2005 - Lecture 1
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
Homework
Read Chapters 1,2 and 9 Due at the beginning of next class:
HW 1Academic Integrity Statement
FYI: Info on Cygwin, Putty, SecureCRT, and Emacs are on the website