View
230
Download
1
Embed Size (px)
Citation preview
1
Beginning Concepts for Problem Solving in C: variables, data types, operators, and formatted IO
BJ Furman
30JAN2010
2
The Plan for Today
The concept of data Constants vs. variables Variables
naming rules data types
Operators and their precedence Practice writing and executing C programs
in ChIDE
3
Learning ObjectivesFollowing completion of today’s lab, you should be able to:
List and explain the basic kinds of data Distinguish between variables and constants Declare integer, floating point, and character variables List the basic data types used in C Identify and explain commonly used operators in C Use C operators correctly according to their placement in the
hierarchy chart Write and execute simple C programs in ChIDE Set up and evaluate expressions and equations using variables,
constants, operators, and hierarchy of operations
4
What and Why?
Data => pieces of information we deal with in the problem solving process
Why is it important to know about data types? Need to know about data types to effectively use a
programming language It’s all just bits the lowest level!
What would you rather work with…int i; float r;i = 3;r = cos(2*i*PI);
or…00000010 10000000 00000000 0000011010000010 10000000 01111111 1111110011001010 00000001 00000000 00000000
etc.
5
Kinds of Data (simplified view)
The basic kinds of data that we will mostly use: Numeric
Integers: Real (floating point) numbers:
Character (are enclosed by single quotes in C) All letters, numbers, and special symbols
Ex. ‘A’, ‘+’, ‘5’
String (are enclosed by double quotes in C) Are combinations of more than one character
Ex. “programming”, “ME 30” Logical (also called ‘Boolean’ named after George Boole an English
mathematician from the early 1800’s) True or False (1 or 0)
6
Kinds of Data - PracticeData Type
1. 17
2. “George”
3. 2.35
4. 0.0023
5. -25
6. ‘m’
7. 4.32E-6
8. “185.3”
9. 0
10. 1
If kind is ‘numeric’, then is it an integer or a floating point number?
7
Constants and Variables Constant
A data element that never changes in your program 5, 62.37, 4.219E-6, “record_string”, ‘$’ i = j + 7; /* which one is the constant? */ first_letter = ‘a’; /* which one is the constant? */
Variable A data element that can take on different values
Its name represents a location (address) in memory i = j + 7; /* which are variables? */ second_letter = ‘b’; /* which is the variable? */
Values are ‘assigned’ using a single equal sign ( = ) Read the statement: i = j + 7;
NOTE!! Variables in C must be ‘declared’ before they can be used!
8
Declaring Variables and Data Types
Variables must be declared before they can be used Gives info to the compiler about:
How many bytes of memory to set aside How to interpret the bytes (data)
Example: int my_var; /* an integer variable my_var */
float sensor1; /* a float variable sensor1 */
char Letter01_a; /* a char variable Letter01_a */ Two parts are needed in the declaration:
Data type designator (e.g., int), (note, a ‘reserved word’) Identifier (i.e., a name: my_var), must be a valid identifier
9
Variable Names See the handout, ‘Notes on Variable Names’
Sequence of lower and/or upper case letters, digits, and underscores
Case sensitive! ex: my_num is not the same as My_num Initial character may not be a digit May not use reserved words as identifiers Keep length to 31 or fewer characters Make the first 8 characters unique Avoid names used by run-time libraries (e.g., log, which is used
in math.h) Avoid using names beginning with underscores Try to use lowercase letters for variable names, and UPPER
CASE letters for macro names (e.g., #define PI 3.14159) Choose names that are meaningful (e.g., light_level instead of
just output)
10
Variable Naming - Practice
Variable Valid? Comments
1 bump_switch
2 sum1
3 sum3.2
4 num-var
5 NAME
6 register
7 1stname
8 lastname 2
9 _overflow
10 signal
11
Data Types and Memory Recall that declaring a variable
sets aside memory and indicates the type of data that will be stored
Considerations in declarations What kind of data will you be working with?
Just whole numbers? Fractions? Characters? Is speed important?
Integer operations are fastest How much memory is available?
Important for embedded systems and microcontrollers What is the range of the data?
From 0 to n, or from –n to +n, etc. What kind of precision do you need?
Precision number of decimal places
12
Data Types
enumArithmetic TypesPointers
Aggregate TypesScalar Typesvoid
Integral Types Floating Types
arrays structs unions
unsigned signed
charshortintlonglong long
floatdoublelong double
Hierarchy of Data Types
(adapted from Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York.)
13
Memory Allocation for Arithmetic Data Types
Size (bytes) Range of Values
Name (alternate) Description AVR GCC MSVC++ AVR GCC MSVC++
char Character or small integer 1 1Signed: -128 to 127 (-2(8-1) to 2(8-1)-1)Unsigned: 0 to 255 (0 to 28-1)
Signed: -128 to 127Unsigned: 0 to 255
short int (short) Short integer 2 2Signed: -32768 to 32767Unsigned: 0 to 65535
Signed: -32,768 to 32,767Unsigned: 0 to 65535
int Integer 2 4Signed: -32768 to 32767Unsigned: 0 to 65535
Signed: -2,147,483,648 to 2,147,483,647Unsigned: 0 to 4,294,967,295
long int (long) Long integer 4 4
Signed: -2,147,483,648 to 2,147,483,647
Unsigned: 0 to 4,294,967,295
Signed: -2,147,483,648 to 2,147,483,647Unsigned: 0 to 4,294,967,295
long long int (long long) Really long integer 8 8Signed: -9.2E+18 to 9.2E+18Unsigned: 0 to 1.8E+19
Signed: -9.2E+18 to 9.2E+18Unsigned: 0 to 1.8E+19
float 'Single-precision' floating point number 4 4 1E 38 (7 decimal digits of
precision) 1E 38 (7 decimal digits of precision)
double 'Double-precision' floating point number 4 8 1E 38 (7 decimal digits of precision)
1E 308 (15 decimal digits of precision)
long doubleLong double-precision floating point number 8
1E 308 (15 decimal digits of precision)
(See the handout, “Notes on Data Types”)
14
Declaration Practice
Declare the following variables: A character variable named PORTA that will hold
only non-negative numbers A variable named up_down that will hold whole
numbers ranging from -20,000 to 20,000 A variable named heat that will hold values from
-20.0 to 350.0 A variable named max_read that needs 8 decimal
digits of precision
For each variable declared, comment on the number of bytes of memory needed and the data range it will cover
15
Operators
Operator: a symbol (or combination of symbols) used to combine variables and constants to produce a value(Overland, B. (1995) C in plain English, MIS Press, New York.)
The variables and constants that get combined are called ‘operands’
How the combining is carried out depends on the precedence and associativity of the operator
Example – identify the operator(s), operands, and results on each line:int i, j = 3;i = j + 7;
16
Operator Precedenceand Associativity
• All operators have the properties of precedence and associativity.
• Precedence has to do with which operations take priority in groupings of operands around adjacent operators
• Associativity has to do with which operations take priority when the operators in an expression have the same precedence
• Use parentheses () to specify a particular grouping order and to make expressions more readable
17
Operator Practice
Identify the operators, operands, and results on each line
int i, count, mult, mult2=1, total_sum;
float total_percentage; i = 1;mult = total_sum = i;count = i + 1;count = count + 1;total_percentage = total_sum / 100; /* a little tricky! */mult1 = count * 17.23;count += 1;mult2 *= 2;
18
Arithmetic with Mixed Data Types
Fundamentally, the computer is not able to arithmetically combine data of different types Arithmetic with integers integer results
int div_int = 8 / 5; /* what is div_int? */
Arithmetic with floating point data floating point results
float div_flt = 8.0 / 5.0; /* what is div_flt? */
Arithmetic with integers and floating point values in the same expressions ??
int div_int = 8.0 / 5; /* what is div_int? */ float div_flt = 8.0 / 5; /* what is div_flt? */
19
Implicit Type Casting
In binary operations (e.g., +, -, /, etc.) with operands of mixed data types, the resultant data type will take the higher order data type of the two operands1
1Cheng, Harry H. (2010). C for Engineers and Scientists: An Interpretive Approach, McGraw-Hill, New York.
long double
double
float
unsigned long long
long long
unsigned long
long
unsigned int
int
unsigned short
short
unsigned char
char
Higher
Lower
20
Expressions and Statements
Expression Any combination of operators, numbers, and names
that evaluates to a single value 5 j = 17 j = i = 10 i + j
Statement A chunk of code that does something (executes)
Terminating an expression with a semicolon (;) turns it into a statement
We will cover other statements later
21
Getting Started with Ch and ChIDE
BJ Furman
11JUL2009
22
What is Ch? an embeddable C/C++ interpreter for cross-
platform scripting, shell programming, 2D/3D plotting, numerical computing, and embedded scripting Developed by Prof. H. Cheng at UC Davis Interpreter vs. compiler
Executes expressions and statements immediately rather than having to construct a complete program and go through compile/link/execute/debug cycles
Superset of C Supports all features of ISO 1990 C Standard (C90) and
major features of C99 Lots more features!
23
More Information on Ch
See The Ch Language Environment, ver. 6.1 User’s Guide Available from: http://www.softintegration.com
24
Starting up Ch
Ch command shell and ChIDE Ch command shell can be invoked
from the Ch icon Can interactively execute C programs,
functions, statements, and expressions
ChIDE can be invoked from the ChIDE icon Can easily access the Ch command shell
from within ChIDE Can easily invoke a 3rd party compiler (e.g.,
MS Visual C++ Express)
25
Ch command shell
26
ChIDE Click on the Ch icon to launch a Ch shell window
27
Laboratory Exercises Work individually unless not enough computers
Take turns at the keyboard if you have to work with a partner Open ChIDE and launch a Ch shell window Open a new window in ChIDE
File | New or Ctrl-N Follow the instructions on the
Lab Project #1 guide sheet Fill out the worksheets Complete the cover page Description is especially important
In your own words, not plagiarized
Save your work on a personal storage device before you leave
28
Formatted Output
BJ Furman
16JUL2009
29
Formatted Output
We use the printf function (stands for ‘print-formatted) to display text and numeric information to the screen printf is available by including the Standard IO
library, stdio.h (more on this later) Ch already “knows” about printf, so it is not
necessary to include stdio.h
Ex. Print a line of textprintf("Hello ME 30!!");
30
printf() – a closer look General form:
printf(“control string”, arg1, arg2,…); Control string
A string enclosed in double quotes that controls the conversion and formatting of zero or more arguments
Arguments are expressions that the function printf acts on Inside the control string will often be conversion specifications
and modifiers that specify how the data from the arguments is to be converted into displayable form
Escape sequences (a \ followed by a letter or combination of digits)) are also used to control the position of the cursor and/or provide literal representations of non-printing or special characters
Ex. Try this in ChIDE
printf("printf example:\n 1+1=%d\n", 1+1);
31
Conversion Specifications (partial list)
ConversionSpecification
Output
%ccharacter (if datum is an int, prints ASCII value corresponding to least significant byte)
%s string of characters
%d or %i decimal integer
%e, E floating point number in e (or E)–notation
%f floating point number (float or double) in decimal notation
%g, Guses %f or %e, E depending on datum value. Trailing zeros are removed
%u unsigned decimal integer
%o octal integer (base 8)
%x, X hexadecimal integer (base 16), lower, Upper case
%% Prints a % sign
Adapted from: http://www.eecs.umich.edu/~bartlett/printf.html
32
Escape Sequences (partial list)
EscapeSequence
Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\“ Double quotation mark
\\ Backslash
\? Literal question mark
http://msdn.microsoft.com/en-us/library/h21280bw(VS.80).aspx
33
Conversion Specification Flags Optional format modifiers that may come before
the conversion character (Darnell & Margolis, 1996)
Flag Meaning
- Left justify
+ Prefix numeric data with a + or – sign. Takes precedence over a blank space if both are given
space Causes negative numbers to be prefixed with a – sign and positive numbers with a space (default is no space for positive numbers)
# No effect for c, d, I, s, and u specifiers. For o, printed value will be prefixed with a zero. For x and X, prefixes value with 0x or 0X. For e, E, f, g, and G, causes results to contain a decimal point, even if precision is zero. For g and G, trailing zeros will not be removed from results as they normally are.
34
Field Width Specification
Optional specification of minimum number of characters to output Will pad to the right or left to fill specified
width if data requires fewer characters Default is pad on the left (i.e., RIGHT justify), but
can specify right pad (i.e., LEFT justify) with the left adjustment flag (the minus sign)
35
Precision Specification
Signified by a period followed by a decimal constant (e.g., %5.2f) Floating point values
Specifies the number of digits to appear after the decimal point
Will round if actual value exceeds the specified precision
Integer values Same meaning as field width specifier, but
overrides it. Will pad the field with zeros on the left until the precision length is reached
36
Short and Long Specifiers
Specifier Meaning
h Corresponding data item is a short int or unsigned short int
l Corresponding data item is a long int or unsigned long int
L Corresponding data item is a long double
Data conversions take place when arguments are passed to the printf function Integers are converted to int Floating point to double
To ensure arguments are cast back to their original types, use short and long specifiers
37
Practice - operator precedence
On paper, determine output of:
int i, j = 3;i = j + 7;i = j / 12 + 5; int k = (j + i * 3); printf(“%d, %d, %d”, i, j, k);
Output:
38
Practice - operator precedence solution
Program Trace:
int i, j = 3; /* j = 3 */
i = j + 7; /* i = 3+7 = 10 */
i = j / 12 + 5; /* i = (3/12)+5 = 9 */
int k = (j + i * 3); /* k=3+27=30 */
printf(“%d, %d, %d”, i, j, k);
Output: 9, 3, 30
39
Formatted input
BJ Furman
18JUL2009
40
scanf() function (just a brief treatment!)
scanf() is like the reverse of printf It reads data entered via the keyboard Similarities to printf():
Needs a format string first Many common format specifiers, which indicate the type of
data expected from the keyboard Which must match the data arguments
Any number of data arguments Differences from printf():
Data argument identifiers must be preceded with an ampersand (&)
The & ahead of the variable signifies the address in memory where the data will be stored (its a pointer to the variable)
Beware!!! Forgetting the & is a common error.
41
scanf() function, cont. Differences from printf(), cont.:
Characters other than a conversion string, a space, a newline character, or a vertical tab must match characters in the input stream
A space, horizontal tab, or newline character in the format string causes scanf() to skip over leading white space up to the next nonspace character
scanf(“Distance= %lf", &num1); Will skip leading spaces before the value num1 Must find a match to the string literal, Distance= (or else
it will stop reading the input and will return the number of successful conversions that were stored (try entering a space before typing Distance=)
Darnell & Margolis (1996)
42
scanf example 1
Prompt the user for a integer, and store it in an integer variable named num1
int num1;
printf("Enter an integer > ");
scanf("%d", &num1);
printf("The value you entered is %d\n", num1);
43
scanf example 2
Prompt the user for a floating point value, and store it in an floating point variable of type double named dbl_num2
double dbl_num2;
printf("Enter a floating point number > ");
scanf("%lf", &dbl_num2);
printf("The value you entered is %G\n", dbl_num2);
44
Anatomy of a C program
BJ Furman
18JUL2009
45
Structured Programming
A formal letter has a structure So does a program in C
Burford FurmanProfessorDept. of Mech. and Aero. EngSan José State UniversitySan Jose, CA 95192-0087
July 20, 2009
Dear Prof. Furman,
I’m writing you to see if I can get into ME 30……
Sincerely,
Jane Student
Title block
Date
Salutation
Body
Closing
Signature
46
Essential Program Structure
/* Programmer’s Block */ Description and documentation of the program#include directives Compiler instructions to access to a library#define directives Compiler instructions for replacement macroglobal variable declarations Declaration of variables with global scopeglobal function declarations Declaration of functions with global scopeint main() Calling of the function ‘main’{
variable declarations Declaration of variables with local scope function declarations Declaration of functions with local scopevariable initializations Initialization of local variablesstatements Statements forming the core of the programreturn 0; Value to return when main() completes
}/* function definitions */function name(parameter list) Header of function (i.e., name and parameters){
statements Statements forming the core of the function}
47
A C program (Fig. 2.1 in H&K, p. 47)
/* Converts distances from miles to kilometers. */
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */
int main(void) {
double miles, kms; /* miles->dist. in miles, kms-> equiv. distance in kms */
/* Get the distance in miles. */printf("Enter the distance in miles> ");scanf(“%lf", &miles);
/* Convert the distance to kilometers. */kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */printf("That equals %f kilometers.\n", kms);
return (0);}
48
A C program Annotated (Fig. 2.1 in H&K, p. 47)
49
References
Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York.
50
Extra Items
51
Memory Stores program instructions and
data Memory (8-bit)Address
0 1 1 0 0 1 1 0
0 1 0 1 0 1 0 0
0 0 0 0 0 0 0 0
0x10FE
0x10FF
0x1100
0xFFFF
Bit 7 6 5 4 3 2 1 0
Each location hasan ‘address’
Each location storesthe information as ‘bits’ Binary ____its
Zero or one
8 bits is one byte Information is ‘coded’ Memory is ‘written’ or ‘read’
Back
52
Hierarchy of Data Types
Back
(adapted from Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York.)
Data Types
enumArithmetic TypesPointers
Aggregate TypesScalar Typesvoid
Integral Types Floating Types
arrays structs unions
unsigned signed
charshortintlonglong long
floatdoublelong double
53
Reserved Words in C
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
You may not use these as variable names
Back
Back
ASCII Table