Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 2: C Programming & Data Types

Similar presentations


Presentation on theme: "Lecture 2: C Programming & Data Types"— Presentation transcript:

1 Lecture 2: C Programming & Data Types
Bryan Burlingame 30 Aug 2017

2 This is a baby, she’s amused
This is a flowchart, it’s funny Ref: xkcd:

3 Announcements I need to mix up the first few lectures
Lab kits are a bit delayed Homework 1 due in two weeks (13 Sept) Homework 2 posted Lab 1 is due this week in lab Read chapters 1 – 3 in the text Always check the syllabus for readings

4 Recall Computers natively work with on/off, 0/1, binary numbers
Binary is similar to decimal Binary: base 2 Decimal: base 10 2,54610 = 2 x x x x 100 10112 = 1 x x x x 20 = 1110

5 Binary to Decimal Binary number only have two value 0/1
Base 2 numbering system A bit: A number in base 2 (binary digit) Decimal numbers have ten values 0 – 9 Base ten numbering system Think scientific notation 6.02E23 = 6 * * * 1021 = 8510= 1 * * * * 20 Range? Largest 8 bit value: = 25510 Largest 16 bit value: =

6 Negative Values Recall: Sign bit 1’s Complement
The computer only deals in 0/1 Humans provide context Sign bit The first bit represents sign = -213, = 213 1’s Complement Flip the bits (change 1’s into 0’s) = - 213, = 213

7 Negative Values (Cont)
2’s Complement Take 1’s complement, add one Start (8410 in this example) Flip bits Add one (notice the carries)

8 Binary to Hexadecimal Hexadecimal (base 16) is a convenient numbering system 0 – 9, A – F (A = 1010, B = 1110, etc Observe 24 = 16, allows four bits (a nyble) to be grouped 11002 = 1210 = 0xC16

9 Binary to Hexadecimal Convert Binary to Hex b

10 Binary to Hexadecimal Convert Binary to Hex
b (grouping 4 bits) d C F h C39Fh C * * * F * 160 = 50,079 12 * * * * 160 = 50,079

11 Representations Decimal (default) Binary Hexadecimal 108 0’01101100
0x6C 108d b 6Ch 10810 6C16 108 dec bin 6C hex Group by 3s with a comma Group by 4s with a space or an underbar Generally don’t group Spoken short form

12 Decimal to binary Many ways, this is how I do it
120 120 < 128, 0 in 7th position 120 > 64, 1 in 6th position 120 – 64 = 56 56 > 32, 1 in 5th position 56 – 32 = 24 24 > 16, 1 in 4th position 24 – 16 = 8 8 = 8, 1 in 3rd position 8 – 8 = 0 Once we hit zero, all other values are zero Why do I do it this way? It is quick when I don’t have a calculator. Your mileage may vary Binary Decimal 1 10 2 100 4 1000 8 10000 16 100000 32 64 128

13 Fundamental Flow of a C Program
Start Calling parameters Available from Operating System Main Return value to Operating System (very important!) End

14 Structured Programming
Sequence Selection IF IF – ELSE SWITCH Repetition WHILE DO – WHILE FOR Subroutines (Functions)

15 Pre-processor directive Main function (statements go between { } )
C Code for D&D 3.15c Programmer’s block Pre-processor directive Main function (statements go between { } ) Declare and initialize variables While loop (repetition structure) return statement

16 Programmer’s Block Include important information (comments) to document the program: Title Date Author Description Inputs/Outputs Algorithm Revision history Add comments using one of two methods: 1. /* put comment between */ (note: traditional C) 2. // comment (note: single line only)

17 # include (pre-processor directive)
Includes a library file for ‘standard io’ functions for things like printing, etc.

18 main() function Your program needs a main() function
Statements go between the braces { } main() ends with the return keyword and usually the value zero If main() runs successfully, it returns a value of zero

19 Declare and initialize variables
Variables must be declared before you can use them

20 Declarations All variables must be “declared” and should be “initialized” Declaration – allocating memory for a variable value, assigning that memory location a name and a format (integer, float, etc.) Initialization – giving a variable a starting value

21 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) This is an interactive slide meant to be answered by the students following a prompt by the instructor. Scalar data types => variable or field that holds a single value Array data type. Array == “collection of identically typed variables stored contiguously in memory” Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York. , p. 164. Integer: whole number that can be negative, positive, or zero: ex. -40, 0, 200, 19339 Real (floating point) Number: whole number plus a decimal part. ex , 1.23e45 Characters: actually, internally, the computer stores characters as numbers. Every character has a unique code. The most commonly used character code is the ASCII (American Standard Code for Information Interchange) code. See Strings are what can be thought of as ‘aggregate data types’, meaning an adjacent collection of one or more scalar data type. In C, strings are represented by an array of characters See Wikipedia on George Boole:

22 Constants and Variables
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; 5 is an integer constant is a floating point constant E-6 is a floating point constant (written in exponential notation, which is good for really large or really small numbers). “record_string” is a string constant. ‘$’ is a character constant. Assignment, the single equals sign, means store the value of the right hand side of the equal sign to the data object (variable) on the left hand side of the equal sign. Note the semicolons at the end of the assignment statement. This is how all statements must be terminated. More on this later. Note the line i = j + 7; /* which one is the constant? */ The stuff after the i = j + 7; is a comment. Anything between /* and */ is for documentation purposes and will not affect the compiled code. Comments are stripped out during preprocessing. NOTE!! Variables in C must be ‘declared’ before they can be used!

23 Declaration example double velocity = 4.565;
Variables should have descriptive names int a = 3434; // what does ‘a’ hold? int current_location = 3434; int curr_loc = 3434; Semicolon Data type Name Initial value

24 C Data Types - Integers Type Size char 1 or 2 bytes (commonly 1 byte)
short At least 2 bytes (commonly 2 bytes) int Most common, at least 2 bytes (commonly 4 bytes) long (long int) At least 4 bytes (commonly 4 bytes) long long int At least 8 bytes (commonly 8 bytes) – relatively new Type Size char 1 or 2 bytes (commonly 1 byte) short At least 2 bytes (commonly 2 bytes) int Most common, at least 2 bytes (commonly 4 bytes) long (long int) At least 4 bytes (commonly 4 bytes) long long int At least 8 bytes (commonly 8 bytes) – relatively new Modifier Comment unsigned Forces the integer to be unsigned, effectively doubling the upper bound signed Forces the integer to be signed (uncommon, used with char) const Relatively new, marks the variable as a constant

25 C Data Types – Floating point
Size float Single precision floating point (usually 4 bytes) double Double precision floating point (usually 8 bytes) long double Many implementations (10 byte, 16 byte, 8 byte)… Type Size char 1 or 2 bytes (commonly 1 byte) short At least 2 bytes (commonly 2 bytes) int Most common, at least 2 bytes (commonly 4 bytes)

26 C Datatypes C’s built-in datatypes have a problem!
No strong standard on how many bits are assigned to each Size is implementation specific Ex: int (integer) Arduino Uno: 16 bits Arduino Due: 32 bits

27 C Data Types – New Types Type Size intN_t
Signed integer of size N bits, where N should be 8, 16, 32, or 64. Example: int8_t is an 8 bit integer uintN_t Unsigned integer of size N bits, where N should be 8, 16, 32, or 64. Example: uint16_t is a 16 bit unsigned integer float_t At least as long as a float (they still can’t get it together, but at least this is testable!) double_t At least as long as a double Type Size char 1 or 2 bytes (commonly 1 byte) short At least 2 bytes (commonly 2 bytes) int Most common, at least 2 bytes (commonly 4 bytes)

28 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 Avoid names used by run-time libraries (e.g., log, which is used in math.h) Try to use lowercase letters for variable names, and UPPER CASE letters for symbolic constants (e.g., #define PI ) Choose names that are meaningful (e.g., light_level instead of just output)

29 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; This is an interactive slide meant to be answered by the students following a prompt by the instructor. int i, j = 3; Declaration of i and j as integer variables. Note that j is assigned the constant integer value of 3 at the same time it is declared. The = sign (assignment) is the operator. j and 3 are the operands. The value of i is not determined. It is likely to be zero, but not necessarily. i = j + 7; Here we have two operators: = (assignment), and + (addition). The operands for the addition operation are j and 7. The operands for the assignment operation are i and j+7. In what order should the operations be carried out? See the next slide, or the handout on ‘Precedence and Associativity’. According to the chart, j+7 is carried out first (result is 3+7=10), and then 10 is assigned to i.

30 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

31 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? */ float div_flt = 8 / 5; /* what is div_flt? */ This is an interactive slide meant to be answered by the students following a prompt by the instructor. Note that on the slides the variables are being declared and initialized at the same time. The initialized value is the value that results when the arithmetic expression is evaluated. int div_int = 8/5 evaluates to 1 There is no fractional part with integers. Any fractional part is truncated, NOT rounded. float div_flt = 8.0/5.0 evaluates to int div_int = 8.0/5 evaluates to 1 Even though to carry out the division, the integer constant 5 is implicitly cast as a float, and the division is done with two floating point values, the assignment to the integer variable div_int leads to the fractional part being truncated. float div_flt = 8.0/5 evaluates to

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

33 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

34 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) Ex. Print a line of text printf("Hello ME 30!!"); Pull the class back together to give a short ‘lecture’ on formatted output. C treats input and output I/O as reading from or writing to a file (sometimes called I/O streams, file streams, or just streams) stdin (standard input), which is usually the keyboard. Used to get input from a person typing at the keyboard. stdout (standard output), which is usually the screen of the computer monitor. Used to display information to a person interacting with your program stderr (standard error), which is the path that all error messages pass, usually also the screen of the computer monitor. The printf function writes formatted data to the standard output stream. Note: the name of the function is case sensitive: Printf() or PRINTF() will not work! Also, the statement must end with a semicolon.

35 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 C Run the example in ChIDE. Point out to the students the control string, the escape sequence \n, the conversion specification %d, and the argument (which is an expression, 1+1, that evaluates to 2). Remove the first \n to show how it removes a line feed. Explain that the conversion specification is like a placeholder for the corresponding data value in the list of arguments. There can be more than one conversion specification if there are multiple corresponding arguments. The first conversion specification corresponds to the first argument and so on from left to right. The conversion specification must appropriately match the data type of the argument or else strange output will result. Try: printf("3.1 is not %d", 3.1); or printf("3 is not %f", 3); printf("printf example: 1+1=%d\n", 1+1); Show the effect of spaces in the control string: printf("printf example: =%d\n", 1+1); Show multiple conversion specifications and arguments: printf("num1=%f, num2=%d, char1='%c' ", 3.1, 5, 'A'); printf("printf example:\n 1+1=%d\n", 1+1);

36 Conversion Specifications (partial list)
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 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 (print an int as a signed decimal number) %e, E floating point number in e, E-notation (note: always one digit to the left of the decimal point, and number of places to the right determined by the precision. Default 6) %f floating point number in decimal notation (default precision is 6 decimal places after the decimal point) %g, G uses %f or %e, E depending on datum value. If value would require exponent less than -4 or greater than the precision, e, E is used. Trailing zeros are removed %u unsigned decimal integer %o octal integer (base 8) %x, X hexadecimal integer (base 16), using lower, upper case %% Prints a % sign Adapted from:

37 Escape Sequences (partial list)
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 Escape sequences ‘escape’ from the otherwise normal printing of the letter or symbol following the \ and execute the specified action

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

39 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) printf ("|%15s| \n", "ME 30 rocks!"); printf ("|%-15s| \n", "ME 30 rocks!"); printf ("|%15.2s| \n", "ME 30 rocks!"); printf ("|%-15.2s| \n", "ME 30 rocks!"); printf ("|%.2s| \n", "ME 30 rocks!"); printf("|ME %d rocks!|\n", 30); printf("|ME %f rocks!|\n", 30); printf("|ME %.0f rocks!|\n", 30.0); printf("|ME %.1f rocks!|\n", 30.0); printf("|ME %5.1f rocks!|\n", 30.0); printf("|ME %.1e rocks!|\n", 30.0); printf("|ME %10.1e rocks!|\n", 30.0); printf("|ME %-10.1e rocks!|\n", 30.0); printf(" |ME %-10.1e rocks!|\n", 30.0); printf("|ME \t %d rocks!|\n", 30);

40 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

41 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

42 References Kochan, S. Programming in C, Fourth Edition (2014)


Download ppt "Lecture 2: C Programming & Data Types"

Similar presentations


Ads by Google