Download presentation
Presentation is loading. Please wait.
Published byCorey Boone Modified over 9 years ago
1
Lecture 4: C Programming & Data Types Bryan Burlingame 24 Feb 2016
2
Announcements Homework due next week Read Ch. 4 – 5 in text No office hours, tonight
3
The Plan for Today Introduce the C Programming Language Describe the structure of a C program Introduce variable declarations Introduce printf
4
Fundamental Flow of a C Program Start Main End Return value to Operating System (very important!) Calling parameters Available from Operating System
5
Structured Programming Sequence Selection IF IF – ELSE SWITCH Repetition WHILE DO – WHILE FOR Subroutines (Functions)
6
C Code for D&D 3.15c Programmer’s block Pre-processor directive Declare and initialize variables While loop (repetition structure) Main function (statements go between { } ) return statement
7
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)
8
# include (pre-processor directive) Includes a library file for ‘standard io’ functions for things like printing, etc.
9
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
10
Declare and initialize variables Variables must be declared before you can use them
11
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
12
12 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)
13
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!
14
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; Data typeNameInitial value Semicolon
15
C Data Types - Integers TypeSize char1 or 2 bytes (commonly 1 byte) shortAt least 2 bytes (commonly 2 bytes) intMost common, at least 2 bytes (commonly 4 bytes) long (long int)At least 4 bytes (commonly 4 bytes) long long intAt least 8 bytes (commonly 8 bytes) – relatively new TypeSize char1 or 2 bytes (commonly 1 byte) shortAt least 2 bytes (commonly 2 bytes) intMost common, at least 2 bytes (commonly 4 bytes) long (long int)At least 4 bytes (commonly 4 bytes) long long intAt least 8 bytes (commonly 8 bytes) – relatively new ModifierComment unsignedForces the integer to be unsigned, effectively doubling the upper bound signedForces the integer to be signed (uncommon, used with char) constRelatively new, marks the variable as a constant
16
C Data Types – Floating point TypeSize char1 or 2 bytes (commonly 1 byte) shortAt least 2 bytes (commonly 2 bytes) intMost common, at least 2 bytes (commonly 4 bytes) TypeSize floatSingle precision floating point (usually 4 bytes) doubleDouble precision floating point (usually 8 bytes) long doubleMany implementations (10 byte, 16 byte, 8 byte)…
17
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
18
C Data Types – New Types TypeSize char1 or 2 bytes (commonly 1 byte) shortAt least 2 bytes (commonly 2 bytes) intMost common, at least 2 bytes (commonly 4 bytes) TypeSize intN_tSigned integer of size N bits, where N should be 8, 16, 32, or 64. Example: int8_t is an 8 bit integer uintN_tUnsigned integer of size N bits, where N should be 8, 16, 32, or 64. Example: uint16_t is a 16 bit unsigned integer float_tAt least as long as a float (they still can’t get it together, but at least this is testable!) double_tAt least as long as a double
19
19 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 3.14159) Choose names that are meaningful (e.g., light_level instead of just output)
20
20 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;
21
21 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
22
22 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? */
23
23 Implicit Type Casting 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 operands 1 1 Cheng, Harry H. (2010). C for Engineers and Scientists: An Interpretive Approach, McGraw-Hill, New York. long double double float unsigned long long long unsigned long long unsigned int int unsigned short short unsigned char char Higher Lower
24
24 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
25
25 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!! " );
26
26 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 printf("printf example:\n 1+1=%d\n", 1+1);
27
27 Conversion Specifications (partial list) Conversion Specification Output %c character (if datum is an int, prints ASCII value corresponding to least significant byte)ASCII value %sstring of characters %d or %idecimal integer %e, Efloating point number in e (or E)–notation %ffloating point number (float or double) in decimal notation %g, G uses %f or %e, E depending on datum value. Trailing zeros are removed %uunsigned decimal integer %ooctal integer (base 8) %x, Xhexadecimal integer (base 16), lower, Upper case %Prints a % sign Adapted from: http://www.eecs.umich.edu/~bartlett/printf.html
28
28 Escape Sequences (partial list) Escape Sequence Represents \aBell (alert) \bBackspace \fFormfeed \nNew line \rCarriage return \tHorizontal tab \vVertical tab \'Single quotation mark \“\“ Double quotation mark \\Backslash \?Literal question mark http://msdn.microsoft.com/en-us/library/h21280bw(VS.80).aspx
29
29 Conversion Specification Flags Optional format modifiers that may come before the conversion character (Darnell & Margolis, 1996) FlagMeaning -Left justify +Prefix numeric data with a + or – sign. Takes precedence over a blank space if both are given spaceCauses 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.
30
30 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)
31
31 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
32
32 Short and Long Specifiers SpecifierMeaning hCorresponding data item is a short int or unsigned short int lCorresponding data item is a long int or unsigned long int LCorresponding 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
33
References Kochan, S. Programming in C, Fourth Edition (2014)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.