Introducing constants, variables and data types March 31.

Slides:



Advertisements
Similar presentations
Principles of Programming Chapter 3 Fundamental of C Programming Language and Basic Input/Output Function 1 NI S1 2009/10.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Introduction to C Programming
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
Types and Variables. Computer Programming 2 C++ in one page!
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
Principles of Programming - NI Chapter 3 Fundamental of C Programming Language and Basic Input/Output Function.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C Programming Lecture 4. Tokens & Syntax b The compiler collects the characters of a program into tokens. Tokens make up the basic vocabulary of a computer.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
Objectives You should be able to describe: Data Types
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.
1 IPC144 Session 11 The C Programming Language. 2 Objectives To format a #define statement correctly To use a #define statement in a C program To construct.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Input & Output: Console
Yu Yuanming CSCI2100B Data Structures Tutorial 3
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
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.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Lecture #5 Introduction to C++
Week 1 Algorithmization and Programming Languages.
Characters and tokens Characters are the basic building blocks in C program, equivalent to ‘letters’ in English language Includes every printable character.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
Introduction to Programming
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
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.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
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.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
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
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
 Lecture 3 Basic Data Types. Overview  The basic data types that C uses: int, short, long, unsigned, char, float, double  Operator: sizeof()  Function:
UniMAP Sem I-09/10EKT150: Computer Programming1 Week 2 – Introduction to Computer and Algorithm.
23 March 2012 Basic Data Types. We will learn about the following: Keywords: int, short, long, unsigned, char, float, double Operator: sizeof Function:
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
7. BASIC TYPES. Systems of numeration Numeric Types C’s basic types include integer types and floating types. Integer types can be either signed or unsigned.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Numbers in ‘C’ Two general categories: Integers Floats
EPSII 59:006 Spring 2004.
Fundamental Data Types
WEEK-2.
Fundamental Data Types
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
Primitive Types and Expressions
DATA TYPES There are four basic data types associated with variables:
Presentation transcript:

Introducing constants, variables and data types March 31

Content Warnings and errors Constants Data types` 2

Warnings and Errors The GCC compiler can produce two kinds of diagnostics: errors and warnings. Each kind has a different purpose: Errors report problems that make it impossible to compile your program. GCC reports errors with the source file name and line number where the problem is apparent. Warnings report other unusual conditions in your code that may indicate a problem, although compilation can (and does) proceed. Warnings may indicate danger points where you should check to make sure that your program really does what you intend 3

Calculation of body mass index 4

Lets make errors on purpose 5 Remove ; Remove &

Building a program with errors 6 Notifies us about the syntactical error Notifies us about the warning Even thought program compiles and ready to run, it will not function correctly, thus pay attention to warnings carefully. Program does not compile because of the syntactical error

Data Variables and Constants Some types of data are preset before a program is used and keep their values unchanged throughout the life of the program. These are constants. Any attempt to modify a CONSTANT will result in error. Other types of data may change or be assigned values as the program runs; these are variables. constant variable

Macro constant 8 preprocessor directives

Preprocessor The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. In many C implementations, it is a separate program invoked by the compiler as the first part of translation. 9 preprocessor compiler linker source code binary code Replaces all directives starting with # Analyzes code and generates object code Links object code with libraries This semester we only use two preprocessor directives #include will be substituted with the content of #define will be substituted with throughout the source file

const specifier The other way to define constants is to use const specifier. 10 What’s the difference between two types of constants?  The directive #define defines constant at compilation time  const can be assigned during program execution, but only once!

Examples 1.Integer constants Positive or negative whole numbers with no fractional part Example: const int MAX_NUM = 10; const int MIN_NUM = -90; 2.Floating-point constants (float or double) Positive or negative decimal numbers with an integer part, a decimal point and a fractional part Example: const double VAL = e2; //(stands for x 10 2 ) 3.Character constants A character enclosed in a single quotation mark Example: const char letter = ‘n’; const char number = ‘1’; printf(“%c”, ‘S’); Output would be: S 11

Enumerated types Enumerated Types are a special way of creating your own Type in C. The type is a "list of key words". Enumerated types are used to make a program clearer to the reader/maintainer of the program. 12

Enumerated types Enumerated Types are Not Strings Enums are Not (Really) Integers It turns out that enumerated types are treated like integers by the compiler. Underneath they have numbers 0,1,2,... etc. You should never rely on this fact 13

Basic Data Types There are 4 basic data types : int float double char 1.int used to declare numeric program variables of integer type whole numbers, positive and negative keyword: int int number; number = 12; -32,768 ~ 32,767 ( 16bit machine)

Basic Data Types 2.float fractional parts, positive and negative keyword: float float height; height = 1.72; 3.double used to declare floating point variable of higher precision or higher range of numbers exponential numbers, positive and negative keyword: double double valuebig; valuebig = 12E-3; 3.4e-38 ~ 3.4e38 ( 16bit machine) 1.7e-308 ~ 1.7e308 ( 16bit machine)

Basic Data Types 4.char equivalent to ‘letters’ in English language Example of characters: Numeric digits: Lowercase/uppercase letters: a - z and A - Z Space (blank) Special characters:,. ; ? “ / ( ) [ ] { } * & % ^ etc single character keyword: char char my_letter; my_letter = 'U’; The declared character must be enclosed within a single quote! -128 ~ 127( 16bit machine)

Difference between integer and floating- point numbers 1.An integer has no fractional part; A floating-point number can have a fractional part. 2.Floating-point numbers can represent a much larger range of values than integers can. 3.For some arithmetic operations, such as subtracting one large number from another, floating-point numbers are subject to greater loss of precision. 4.Floating-point values are often approximations of a true value. 5.Floating-point operations are normally slower than integer operations.

Primary data types in C

Floating point representation float Simplified example

Double precision representation C allows for a third floating-point type: long double. The intent is to provide for even more precision than double. However, C guarantees only that long double is at least as precise as double. double

Hierarchy of Integer Types  C offers three adjective keywords to modify the basic integer type: short, long, and unsigned.  The type short int or, more briefly, short may use less storage than int, thus saving space when only small numbers are needed. Like int, short is a signed type.  The type long long int, may use more storage than long, thus enabling you to express even larger integer values. Like int, long long is a signed type.  The type unsigned int, or unsigned, is used for variables that have only nonnegative values. For example, a 16-bit unsigned int allows a range from 0 to in value instead of from –32768 to

Why Multiple Integer Types? The idea is to fit the types to the machine. The most common practice today is to set up long long as 64 bits, long as 32 bits, short as 16 bits, and int to either 16 bits or 32 bits, depending on the machine's natural word size. The minimum range for both short and int is –32,767 to 32,767, corresponding to a 16-bit unit, and the minimum range for long is –2,147,483,647 to 2,147,483,647, corresponding to a 32-bit unit.

When do you use the various int types? First, consider unsigned types. It is natural to use them for counting because you don't need negative numbers, and the unsigned types enable you to reach higher positive numbers than the signed types. Use the long type if you need to use numbers that long can handle and that int cannot. Similarly, use long long if you need 64-bit integer values. Octal and hexadecimal constants are treated as type int unless the value is too large. Then the compiler tries unsigned int. If that doesn't work, it tries, in order, long, unsigned long, long long, and unsigned long long.

Integer Overflow The unsigned integer j is acting like a car's odometer. When it reaches its maximum value, it starts over at the beginning. The integer i acts similarly. The main difference is that the unsigned int variable j, like an odometer, begins at 0, but the int variable i begins at –

Octal and Hexadecimal C assumes that integer constants are decimal, or base 10, numbers. Octal (base 8) and hexadecimal (base 16) numbers are popular with many programmers. Because 8 and 16 are powers of 2, and 10 is not, these number systems occasionally offer a more convenient way for expressing computer-related values. HexadecimalDecimalBinary  When dealing with a large number of bits, it is more convenient and less error-prone to write the binary numbers in hex or octal. VS

Displaying Octal and Hexadecimal To display an integer in octal notation instead of decimal, use %o instead of %d. To display an integer in hexadecimal, use %x. If you want to display the C prefixes, you can use specifiers %#o, %#x, and %#X to generate the 0, 0x, and 0X prefixes, respectively dec = 100; octal = 144; hex = 64 dec = 100; octal = 0144; hex = 0x64

Printing short, long, long long, and unsigned types To print an unsigned int number, use the %u notation. To print a long value, use the %ld format specifier. %hd displays a short integer in decimal form, and %ho displays a short integer in octal form. Both the h and l prefixes can be used with u for unsigned types.

When the value is written in binary format as a 32-bit number, it looks like Note that using the %d specifier for the unsigned variable produces a negative number! Printing short, long, long long, and unsigned types The reason for this is that the unsigned value and the signed value – have exactly the same internal representation in memory on our system. Using the %hd specifier persuaded printf() to look at just the last 16 bits; therefore, it displayed the value as 1

The scanf function Read data from the standard input device (usually keyboard) and store it in a variable. General format: scanf(“%d”, &variable); Ampersand (&) operator : C address of operator it passes the address of the variable instead of the variable tells the scanf() where to find the variable to store the new value variable 0x1240x1280x12C0x130 address: &variable  0x128 4 bytes or other specifiers depending on the variable type memory:

The scanf function If you want the user to enter more than one value, you serialize the inputs. You can serialize input

Common Conversion Identifiers 31 Common Conversion Identifier used in printf() and scanf() functions. printfscanf int%d float%f double%f%lf char%c string%s

Nonprinting Characters The single-quote technique is fine for characters, digits, and punctuation marks. Some of the characters are nonprinting. For example, some represent actions such as backspacing or going to the next line or making the terminal bell ring (or speaker beep) There are two ways to define such variables. 1.Use reserved sequences 2.Use numeric codes form the character table (ASCII codes)

Partial listing of ASCII code

Printing Characters

The showf_pt.c Program The printf() function uses the %f format specifier to print type float and double numbers using decimal notation, and it uses %e to print them in exponential notation To correctly print out dip use %LF and %LE Then the output will be

Floating-Point Overflow and Underflow Suppose the biggest possible float value on your system is about 3.4E38 and you do this This is an example of overflow—when a calculation leads to a number too large to be expressed. The behavior for this case used to be undefined, but now C specifies that toobig gets assigned a special value that stands for infinity and that printf() displays either inf or infinity (or some variation on that theme) for the value.

Floating-Point Round-off Errors Take a number, add 1 to it, and subtract the original number. What do you get? You get 1. A floating-point calculation, such as the following, may give another answer:  older gcc on Linux  Turbo C  clang on Mac OS, MSVC++ Output Compiler

Type Sizes

The typesize.c program The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine- dependent data sizes in your programs.