CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Constants and Literals Gabriel Hugh Elkaim Spring 2012.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
Chapter 10.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Structure of a C program
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 2 Data Types, Declarations, and Displays
C Formatted Input/Output /* Using Integer Conversion Specifiers */ #include int main ( ) { printf( "%d\n", 455 ); printf( "%i\n", 455 ); printf( "%d\n",
String Escape Sequences
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Basic Elements of C++ Chapter 2.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Functions Gabriel Hugh Elkaim Spring 2012.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Modules and Scope Gabriel Hugh Elkaim Spring 2013.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Constants and Literals Gabriel Hugh Elkaim Spring 2013.
A First Book of ANSI C Fourth Edition
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Input & Output: Console
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Programming I Introduction Introduction The only way to learn a new programming language is by writing programs in it. The first program to.
C-Language Keywords(C99)
Constants in C A Presentation On Department of Computer & Information Technology, M.S.P.V.L. Polytechnic College, Pavoorchatram.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Week 1 Algorithmization and Programming Languages.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Pointers Gabriel Hugh Elkaim Spring 2012.
Introduction to Programming
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
DATA TYPE AND DISPLAY Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
C++ Basics Tutorial 5 Constants. Topics Covered Literal Constants Defined Constants Declared Constants.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
Variables Symbol representing a place to store information
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Characters and Strings
1 Objects Types, Variables, and Constants Chapter 3.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Constants and Literals Gabriel Hugh Elkaim Spring 2012.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Introduction to ‘c’ language
ECE Application Programming
Wel come.
Revision Lecture
Chapter 18 I/O in C.
Input and Output Lecture 4.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
C++ Basics.
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
EECE.2160 ECE Application Programming
Presentation transcript:

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Constants and Literals Gabriel Hugh Elkaim Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Convert Temperature Want to write a program to convert the temperature from Fahrenheit to Celsius for a range of temperatures. Demonstrates a loop and use of literals

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 The Code #include /* print Fahrenheit-Celsius table for fahr = 0, 20,..., 300 */ main() { int fahr, celsius; int lower, upper, step; lower = 0;// lower limit of temperature table upper = 300;// upper limit step = 20;// step size fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%d%\t%d\n", fahr, celsius); fahr = fahr + step; }

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Careful with types celsius = 5 * (fahr - 32) / 9;

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Example unsigned int a; unsigned int c; #define b 2 void main(void) { a = 5; c = a + b; printf("a=%d, b=%d, c=%d\n", a, b, c); } A Simple C Program Literal Constants Literal

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Literal Constants Definition A literal or a literal constant is a value, such as a number, character or string, which may be assigned to a variable or a constant. It may also be used directly as a function parameter or an operand in an expression. Literals –Are "hard coded" values –May be numbers, characters or strings –May be represented in a number of formats (decimal, hexadecimal, binary, character, etc.) –Always represent the same value (5 always represents the quantity five)

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Constant vs. Literal What's the difference? Terms are used interchangeably in most programming literature A literal is a constant, but a constant is not a literal –#define MAXINT –const int MAXINT = ; For purposes of this presentation: –Constants are labels that represent a literal –Literals are values, often assigned to symbolic constants and variables

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Literal Constants Four basic types of literals: –Integer –Floating Point –Character –String Integer and Floating Point are numeric type constants: –Commas and spaces are not allowed –Value cannot exceed type bounds –May be preceded by a minus sign

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Integer Literals Decimal (Base 10) Cannot start with 0 (except for 0 itself) Cannot include a decimal point Valid Decimal Integers: Invalid Decimal Integers: ,

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Integer Literals Hexadecimal (Base 16) Must begin with 0x or 0X (that’s zero-x) May include digits 0-9 and A-F / a-f Valid Hexadecimal Integers: Invalid Hexadecimal Integers: 0x0x1 0x0A2B 0xBEEF 0x5.3 0EA120xEG53h

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Integer Literals Octal (Base 8) Must begin with 0 (zero) May include digits 0-7 Valid Octal Integers: Invalid Octal Integers: o o While Octal is still part of the ANSI specification, almost no one uses it anymore.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Integer Literals Binary (Base 2) Must begin with 0b or 0B (that’s zero-b) May include digits 0 and 1 Valid Binary Integers: Invalid Binary Integers: 0b 0b10b b b12 10b ANSI C does not specify a format for binary integer literals. However, this notation is supported by most compilers.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Integer Literals Qualifiers Like variables, literals may be qualified A suffix is used to specify the modifier –‘U’ or ‘u’ for unsigned: 25u –‘L’ or ‘l’ for long: 25L –'F' or 'f' for float: 10f or 10.25F Suffixes may be combined: 0xF5UL –Note: U must precede L Numbers without a suffix are assumed to be signed and short

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Floating Point Literals Decimal (Base 10) Like decimal integer literals, but decimal point is allowed ‘e’ notation is used to specify exponents ( ke±n  k  10 ±n ) Valid Floating Point Literals: Invalid Floating Point Literals: 2.56e e f 0x5Ae F2.33

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Character Literals Specified within single quotes ( ' ) May include any single printable character May include any single non-printable character using escape sequences (e.g. '\0' = NUL) (also called digraphs) Valid Characters: 'a', 'T', '\n', '5', ' ' (space) Invalid Characters: 'me', '23', '''

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 String Literals Specified within double quotes ( " ) May include any printable or non-printable characters (using escape sequences) Usually terminated by a null character ‘ \0 ’ Valid Strings: "Microchip", "Hi\n", "PIC", "He said, \"Hi\"" Invalid Strings: "He said, "Hi""

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 String Literals Declarations Strings are a special case of arrays If declared without a dimension, the null character is automatically appended to the end of the string: char color[3] = "RED"; Is stored as: color[0] = 'R' color[1] = 'E' color[2] = 'D' NOT a complete string – no '\0' at end char color[] = "RED"; Is stored as: color[0] = 'R' color[1] = 'E' color[2] = 'D' color[3] = '\0' Example 1 – Wrong WayExample 2 – Right Way

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 String Literals How to Include Special Characters in Strings Escape Sequence Character ASCII Value \a \b \t \n \v \f \r \" \' \? \\ \0 BELL (alert) Backspace Horizontal Tab Newline (Line Feed) Vertical Tab Form Feed Carriage Return Quotation Mark (") Apostrophe/Single Quote (') Question Mark (?) Backslash (\) Null

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Example String Literals How to Include Special Characters in Strings This string includes a newline character Escape sequences may be included in a string like any ordinary character The backslash plus the character that follows it are considered a single character and have a single ASCII value char message[] = "Please enter a command…\n"

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Symbolic Constants Constants –Once assigned, never change their value –Make development changes easy –Eliminate the use of "magic numbers" –Two types of constants Text Substitution Labels Variable Constants (!!??) Definition A constant or a symbolic constant is a label that represents a literal. Anywhere the label is encountered in code, it will be interpreted as the value of the literal it represents.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Some texts on C declare constants like: This is not efficient for an embedded system: A variable is allocated in program memory, but it cannot be changed due to the const keyword This is not the traditional use of const In the vast majority of cases, it is better to use #define for constants Symbolic Constants Constant Variables Using const Example const float PI = ;

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Symbolic Constants Text Substitution Labels Using #define Defines a text substitution label Syntax #define label text Example #define PI #define mol 6.02E23 #define MCU "PIC24FJ128GA010" #define COEF 2 * PI Each instance of label will be replaced with text by the preprocessor unless label is inside a string No memory is used in the microcontroller

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Note: a #define directive is NEVER terminated with a semi-colon (;), unless you want that to be part of the text substitution. Example Symbolic Constants #define Gotchas #define MyConst 5; c = MyConst + 3; c = 5; + 3;

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Example Symbolic Constants Initializing Variables When Declared #define CONSTANT1 5 const CONSTANT2 = 10; int variable1 = CONSTANT1; int variable2; // Cannot do: int variable2 = CONSTANT2 A constant declared with const may not be used to initialize a global or static variable when it is declared (though it may be used to initialize local variables…)

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Lab Exercise 2 Symbolic Constants

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Symbolic Constants Open the lab Project: On the class website Examples -> Lab2.zip 1 1 Open MPLAB ® X and select Open Project Icon (Ctrl + Shift + O) Open the project listed above. If you already have a project open in MPLAB X, close it by “right clicking” on the open project and selecting “Close”

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Symbolic Constants Compile and run the code: 2 2 Click on the Debug Project button. Debug Project Continue If no errors are reported, click on Continue button to start the program. Pause Click on the Pause button.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Symbolic Constants Expected Results (1): 5 5 The UART 1 Output window should show the text that is output by the program, indicating the values of the two symbolic constants in the code.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Symbolic Constants Expected Results (2): 6 6 CONSTANT1 has no address Only CONSTANT2 can be added to Watches Window Only CONSTANT2 can be added to Watches Window CONSTANT1 cannot be added CONSTANT1 cannot be added CONSTANT2 has address of 0x8CC

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Symbolic Constants Expected Results (3): CONSTANT1 not in Program Memory Program Memory only contains CONSTANT2 CONSTANT2 has a value of 0x00CC 7 7 CONSTANT2 has the address x0BCC

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 02 Conclusions Constants make code more readable Constants improve maintainability #define should be used to define constants #define constants use no memory, so they may be used freely const should never be used in this context (it has other uses…)

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Standard Library Function Used to write text to the "standard output" Normally a computer monitor or printer Often the UART in embedded systems SIM Uart1 window in MPLAB-SIM

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Standard Library Function Syntax printf(ControlString, arg1,…argn); Example int a = 5, b = 10; printf("a = %d\nb = %d\n", a, b); Result: a = 5 b = 10 Everything printed verbatim within string except %d's which are replaced by the argument values from the list NOTE: the 'd' in %d is the conversion character. (See next slide for details)

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Conversion Characters for Control String Conversion Character Meaning %c %s %d %o %u %x %X %f %e %E %g %G Single character String (all characters until '\0') Signed decimal integer Unsigned octal integer Unsigned decimal integer Unsigned hexadecimal integer with lowercase digits (1a5e) As x, but with uppercase digits (e.g. 1A5E) Signed decimal value (floating point) Signed decimal with exponent (e.g. 1.26e-5) As e, but uses E for exponent (e.g. 1.26E-5) As e or f, but depends on size and precision of value As g, but uses E for exponent

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Gotchas The value displayed is interpreted entirely by the formatting string: printf("ASCII = %d", 'a'); will output: ASCII = 97 A more problematic string: printf("Value = %d", 6.02e23); will output: Value = Incorrect results may be displayed if the format type doesn't match the actual data type of the argument

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Useful Format String Examples for Debugging Print a 16-bit hexadecimal value with a "0x" prefix and leading zeros if necessary to fill a 4 hex digit value: #Specifies that a 0x or 0X should precede a hexadecimal value (has other meanings for different conversion characters) 06Specifies that 6 characters must be output (including 0x prefix), zeros will be filled in at left if necessary xSpecifies that the output value should be expressed as a hexadecimal integer printf("Address of x = %#06x\n", x_ptr);

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 printf() Useful Format String Examples for Debugging Same as previous, but force hex letters to uppercase while leaving the 'x' in '0x' lowercase: 04Specifies that 4 characters must be output (no longer including 0x prefix since that is explicitly included in the string), zeros will be filled in at left if necessary XSpecifies that the output value should be expressed as a hexadecimal integer with uppercase A-F printf("Address of x = 0x%04X\n", x_ptr);

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Lab Exercise 3 printf() Library Function

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 03 printf() Library Function Open the lab Project: On the class website Examples -> Lab3.zip 1 1 Open MPLAB ® X and select Open Project Icon (Ctrl + Shift + O) Open the Project listed above. If you already have a project open in MPLAB X, close it by “right clicking” on the open project and selecting “Close”

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 03 printf() Library Function Compile and run the code: 2 2 Click on the Debug Project button. Debug Project Continue If no errors are reported, click on Continue button to start the program. Pause Wait for the UART1 Output to finish the click on the Pause button. printf() Library Function

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 03 printf() Library Function Expected Results (1): 5 5 The UART1 Output window should show the text that is output by the program by printf(), showing the how values are printed based on the formatting character used in the control string.

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Lab 03 printf() Library Function Expected Results (2): printf("'Microchip' as decimal (d): %d\n", "Microchip"); Microchip printf("'Microchip' as string (s): %s\n", "Microchip"); printf("6.02e23 as decimal (d): %d\n", 6.02e23); e+23 printf("6.02e23 as exponent (e): %e\n", 6.02e23); a 25 printf("2.55 as decimal (d): %d\n", 2.55); printf("2.55 as float (f): %f\n", 2.55); printf("'a' as decimal (d): %d\n", 'a'); printf("'a' as character (c): %c\n", 'a'); printf("25 as decimal (d): %d\n", 25); Detailed Analysis: Line of Code From Demo Project Output

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Exercise 03 Conclusions printf() has limited use in embedded applications themselves It is very useful as a debugging tool It can display data almost any way you want Projects that use printf() must: MPLAB ® X –Configure a heap (done in MPLAB ® X -IDE) –Include the stdio.h header file

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 Questions?

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012

CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012