Beginning Concepts for Problem Solving in C variables

Beginning Concepts for Problem Solving in C: variables, data types, operators, and formatted IO BJ Furman 30 JAN 2010 1

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 Ch. IDE 2

Learning Objectives Following 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 Ch. IDE Set up and evaluate expressions and equations using variables, constants, operators, and hierarchy of operations 3

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 10000000110 10000000 0111111100 11001010 00000001 00000000 etc. 4

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 String (are enclosed by double quotes in C) Are combinations of more than one character Ex. ‘A’, ‘+’, ‘ 5’ 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) 5

Kinds of Data - Practice Data 1. 17 2. “George” 3. 2. 35 4. 0. 0023 5. -25 6. ‘m’ 7. 4. 32 E-6 8. “ 185. 3” 9. 0 10. 1 Type If kind is ‘numeric’, then is it an integer or a floating point number? 6

Constants and Variables Constant A data element that never changes in your program 5, 62. 37, 4. 219 E-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! 7

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 sensor 1; /* a float variable sensor 1 */ char Letter 01_a; /* a char variable Letter 01_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 8

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) 9

Variable Naming - Practice Variable 1 bump_switch 2 sum 1 3 sum 3. 2 4 num-var 5 NAME 6 register 7 1 stname 8 lastname 2 9 _overflow 10 signal Valid? Comments 10

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? Is speed important? Important for embedded systems and microcontrollers What is the range of the data? Integer operations are fastest How much memory is available? Just whole numbers? Fractions? Characters? From 0 to n, or from –n to +n, etc. What kind of precision do you need? Precision number of decimal places 11

Hierarchy of Data Types (adapted from Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3 rd ed. , Springer, New York. ) Data Types void Scalar Types Aggregate Types arrays Pointers Arithmetic Types Integral Types unsigned char short int long structs unions enum Floating Types float double long double 12

Memory Allocation for Arithmetic Data Types (See the handout, “Notes on Data Types”) Size (bytes) Name (alternate) Description char short int (short) int Range of Values AVR GCC MSVC++ Character or small integer 1 1 Signed: -128 to 127 (-2 (8 -1) to 2(8 -1)-1) Unsigned: 0 to 255 (0 to 2 8 -1) Signed: -128 to 127 Unsigned: 0 to 255 Short integer 2 2 Signed: -32768 to 32767 Unsigned: 0 to 65535 Signed: -32, 768 to 32, 767 Unsigned: 0 to 65535 4 Signed: -32768 to 32767 Unsigned: 0 to 65535 Signed: -2, 147, 483, 648 to 2, 147, 483, 647 Unsigned: 0 to 4, 294, 967, 295 Integer 2 AVR GCC MSVC++ long int (long) Long integer 4 4 Signed: -2, 147, 483, 648 to 2, 147, 483, 647 Unsigned: 0 to 4, 294, 967, 295 long int (long) Really long integer 8 8 Signed: -9. 2 E+18 to 9. 2 E+18 Unsigned: 0 to 1. 8 E+19 float 'Single-precision' floating point number 4 4 1 E 38 (7 decimal digits of precision) double 'Double-precision' floating point number 4 8 1 E 38 (7 decimal digits of precision) 1 E 308 (15 decimal digits of precision) long double Long double-precision floating point number 8 1 E 308 (15 decimal digits of precision) 13

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 14

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; 15

Operator Precedence and 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 16

Operator Practice Identify the operators, operands, and results on each line int i, count, mult 2=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! */ mult 1 = count * 17. 23; count += 1; mult 2 *= 2; 17

Arithmetic with Mixed Data Types Fundamentally, the computer is not able to arithmetically combine data of different types Arithmetic with integers integer results /* what is div_int? */ Arithmetic with floating point data floating point results int div_int = 8 / 5; 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? */ 18

Implicit Type Casting Higher 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 operands 1 long double float unsigned long unsigned long unsigned int unsigned short unsigned char 1 Cheng, Harry H. (2010). C for Engineers and Scientists: An Interpretive Approach, Mc. Graw-Hill, New York. Lower 19

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 20

Getting Started with Ch and Ch. IDE BJ Furman 11 JUL 2009 21

What is Ch? an embeddable C/C++ interpreter for crossplatform scripting, shell programming, 2 D/3 D plotting, numerical computing, and embedded scripting Developed by Prof. H. Cheng at UC Davis Interpreter vs. compiler Superset of C Executes expressions and statements immediately rather than having to construct a complete program and go through compile/link/execute/debug cycles Supports all features of ISO 1990 C Standard (C 90) and major features of C 99 Lots more features! 22

More Information on Ch See The Ch Language Environment, ver. 6. 1 User’s Guide Available from: http: //www. softintegration. com 23

Starting up Ch command shell and Ch. IDE Ch command shell can be invoked from the Ch icon Can interactively execute C programs, functions, statements, and expressions Ch. IDE can be invoked from the Ch. IDE icon Can easily access the Ch command shell from within Ch. IDE Can easily invoke a 3 rd party compiler (e. g. , MS Visual C++ Express) 24

Ch command shell 25

Ch. IDE Click on the Ch icon to launch a Ch shell window 26

Laboratory Exercises Work individually unless not enough computers Open Ch. IDE and launch a Ch shell window Open a new window in Ch. IDE Take turns at the keyboard if you have to work with a partner 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 27

Formatted Output BJ Furman 16 JUL 2009 28

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 text printf("Hello ME 30!!"); 29

printf() – a closer look General form: printf(“control string”, arg 1, arg 2, …); 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 Ch. IDE printf("printf example: n 1+1=%dn", 1+1); 30

Conversion Specifications (partial list) Conversion Specification Output %c character (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, G uses %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 31

Escape Sequences (partial list) Escape Sequence 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/h 21280 bw(VS. 80). aspx 32

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 0 x or 0 X. 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. 33

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) 34

Precision Specification Signified by a period followed by a decimal constant (e. g. , %5. 2 f) Floating Specifies the number of digits to appear after the decimal point Will round if actual value exceeds the specified precision Integer point 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 35

Short and Long Specifiers 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 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 36

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”, i, j, k); Output: 37

Practice - operator precedence solution Program Trace: int i, j = 3; /* i = j + 7; */ i = j / 12 + 5; /* int k = (j + i * 3); printf(“%d, %d”, Output: j = 3 */ /* i = 3+7 = 10 i = (3/12)+5 = 9 */ /* k=3+27=30 */ i, j, k); 9, 3, 30 38

Formatted input BJ Furman 18 JUL 2009 39

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. 40

scanf() function, cont. Differences from printf(), cont. : Darnell & Margolis (1996) 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", &num 1); Will skip leading spaces before the value num 1 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=) 41

scanf example 1 Prompt the user for a integer, and store it in an integer variable named num 1 int num 1; printf("Enter an integer > "); scanf("%d", &num 1); printf("The value you entered is %dn", num 1); 42

scanf example 2 Prompt the user for a floating point value, and store it in an floating point variable of type double named dbl_num 2 double dbl_num 2; printf("Enter a floating point number > "); scanf("%lf", &dbl_num 2); printf("The value you entered is %Gn", dbl_num 2); 43

Anatomy of a C program BJ Furman 18 JUL 2009 44

Structured Programming A formal letter has a structure So does a program in C Burford Furman Title Professor Dept. of Mech. and Aero. Eng San José State University San Jose, CA 95192 -0087 block July 20, 2009 Date Dear Prof. Furman, Salutation I’m writing you to see if I can get into ME 30… … Body Sincerely, Closing Jane Student Signature 45

Essential Program Structure /* Programmer’s Block */ #include directives #define directives global variable declarations global function declarations int main() { variable declarations function declarations variable initializations statements return 0; } /* function definitions */ function name(parameter list) { statements } Description and documentation of the program Compiler instructions to access to a library Compiler instructions for replacement macro Declaration of variables with global scope Declaration of functions with global scope Calling of the function ‘main’ Declaration of variables with local scope Declaration of functions with local scope Initialization of local variables Statements forming the core of the program Value to return when main() completes Header of function (i. e. , name and parameters) Statements forming the core of the function 46

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 int main(void) { double miles, kms; /* conversion constant */ /* 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); } 47

A C program Annotated (Fig. 2. 1 in H&K, p. 47) 48

References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3 rd ed. , Springer, New York. 49

Extra Items 50

Memory Stores program instructions and data Each location has an ‘address’ Each location stores the information as ‘bits’ Binary ____its Zero or one Memory (8 -bit) Address 0 x 10 FE 0 1 1 0 0 x 10 FF 0 1 0 1 0 0 0 x 1100 0 0 x. FFFF Bit 7 6 5 4 3 2 1 0 8 bits is one byte Information is ‘coded’ Memory is ‘written’ or ‘read’ Back 51

Hierarchy of Data Types (adapted from Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3 rd ed. , Springer, New York. ) Data Types void Scalar Types Aggregate Types arrays Pointers Arithmetic Types Integral Types unsigned char short int long structs unions enum Floating Types float double long double Back 52

Reserved Words in C You may not use these as variable names auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Back 53

ASCII Table Back 54
- Slides: 54