• No results found

Chapter 3 Variables and Expressions. Last modified: 9/21/21

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 3 Variables and Expressions. Last modified: 9/21/21"

Copied!
73
0
0

Loading.... (view fulltext now)

Full text

(1)

1

Chapter 3

Variables and Expressions

Last modified: 9/21/21

(2)

Outline

Reserved words

Identifiers

Variables

Data Types and Constants

The Assignment Operators

Reading and printing values

Working with Arithmetic Expressions

2

(3)

Reserved Words and Identifiers

A program is a sequence of reserved words and user-defined identifiers

§ Reserved word

— Word that has a specific meaning in C

Ø Ex: int, return

§ Identifier

— Word used to name and refer to a data element or object manipulated by the program.

3

(4)

Valid Identifier Names

4

§ Begins with a letter or underscore symbol

§ Consists of letters, digits, or underscores only

§ Cannot be a C reserved word

§ Case sensitive

— Total ≠ total ≠ TOTAL

§ Examples:

distance milesPerHour _voltage goodChoice high_level MIN_RATE

(5)

Invalid Identifier Names

5

§ Does not begin with a letter or underscore symbol or

§ Contains other than letters, digits, and underscore or

§ Is a C reserved word

§ Examples

x-ray

2ndGrade

$amount two&four after five return

(6)

Identifier Name Conventions

§ Standard practice, not required by C language

— Normally lower case

— Constants upper case

§ Multi-word

— Underscore between words or

— Camel case - each word after first is capitalized distance

TAX_RATE

miles_per_hour milesPerHour

CONSTANT

6

(7)

Variable

Variable: a symbolic name for a memory location where a value can be stored for use by a program

§ Programmer doesn’t have to worry about specifying (or even knowing) the value of the location’s address

§ Value can change during program execution

§ At any time, can hold only one value

§ Whenever a new value is placed into a variable, the new value replaces the previous value.

7

(8)

Variables Names

§ Must be a valid identifier name

§ Variables must be declared with a name and a data type before they can be used in a program

§ Should not be the name of a standard function or variable

§ Should be descriptive; the name should be reflective of the variable’s use in the program (readability)

§ Abbreviations should be commonly understood

— Ex. amt = amount

8

(9)

Variable/Named Constant Declaration Syntax

9

optional_modifier data_type name_list;

§ optional_modifier – type modifier

— Used to distinguish between signed and unsigned integers

Ø The default is signed

— Used to specify size (short, long)

— Used to specify named constant with const keyword

§ data_type - specifies the type of value; allows the compiler to

know what operations are valid and how to represent a particular value in memory

§ name_list – program identifier names

§ Examples:

§ int test-score;

§ const float TAX_RATE = 6.5;//const for maintainability

(10)

Numeric Data Types

Whole numbers

(Integer) Real numbers

(Floating-point)

short int long float

10

double long double

(11)

Storage sizes and ranges

Every type has a size and range of values associated with it.

1. The range is determined by the amount of storage that is allocated to store a value belonging to that type of data.

2. In general, that amount of storage is not defined in the language. It

typically depends on the computer you’re running, and is, therefore, called implementation- or machine-dependent.

3. For example, an integer might take up 32 bits on your computer, or it might be stored in 64. You should never write programs that make any assumptions about the size of your data types (portability)!

4. The language standards only guarantees that a minimum amount of storage will be set aside for each basic data type.

5. For example, it’s guaranteed that an integer value will be stored in a minimum of 32 bits of storage, which is the size of a “word” on many computers.

11

(12)

Data Types and Typical Sizes

12

Type Name Memory Used

Size Range Precision Guarantee

short

(= short int)

2 bytes -32,768 to 32,767 N/A 16 bits

int 4 bytes -2,147,483,648 to

2,147,483,647 N/A 16 bits

long

(= long int)

8 bytes -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807 N/A 32 bits

float 4 bytes approximately

10-38 to 1038

7 digits 6 digits

double 8 bytes approximately

10-308 to 10308

15 digits 10 digits

long double 10 bytes approximately 10-4932 to 104932

19 digits 10 digits

(13)

Determining Data Type Size

§ sizeof operator

— Returns size of operand in bytes

— Operand can be a data type

§ Examples:

13

(14)

Characters

Type Name Memory

Used Sample Size Range

char 1 byte All ASCII characters

ASCII = American Standard Code for Information Interchange

www.asciitable.com 14

(15)

Boolean Data Type

§ Data type: _Bool

— Can only store 0 & 1

— Non zero value will be stored as 1

§ Data type : bool

— <stdbool.h> defines bool, true, and false

§ Any expression

— 0 is false

— Non-zero is true

15

(16)

Variable Declaration Examples

16

(17)

Assigning Values to Variables

17

§ Allocated variables without initialization have an undefined value.

§ We will use three methods for assigning a value to a variable

— Initial value

Ø In the declaration statement

— Processing

Ø the assignment statement

— Input

Ø scanf function

(18)

Initializing Variables

§ Initializing variables in declaration statements

18

(19)

Assignment Operator =

§ Assigns a value to a variable

§ Binary operator (has two operands), not the same as "equal to" in mathematics

§ General Form:

l_value = r_value

— Most common examples of l_values (left-side)

Ø A simple variable

Ø A pointer dereference (in later chapters)

— r_values (right side) can be any valid expression

§ Assignment expression has value of assignment

§ Allows us to do something like a = b = 0;

19

(20)

Example Assignment Statement

§ Statement

§ Means:

Evaluate the expression on the right and put the result in the memory location named x

§ If the value stored in y is 18, then 23 will be stored in x

5 is literal value

20

(21)

Other Example Assignments

§ Example:

l_value: distance r_value: rate * time

§ Other Examples:

21

(22)

Terminal Output

What can be output?

§ Any data can be output to standard output (stdout), the terminal display screen

— Literal values

— Variables

— Constants

— Expressions (which can include all of above)

§ printf function:

The values of the variables are passed to printf

Go Tigers!

22

(23)

Syntax: printf function

23

printf(format_string, expression_list)

— Format_string specifies how expressions are to be printed

Ø Contains placeholders for each expression

— Placeholders begin with % and end with type

— Expression list is a list of zero or more expressions separated by commas

— Returns number of characters printed

(24)

Typical Integer Placeholders

— %d or %i - for integers, %l for long

— %o - for integers in octal

— %x – for integers in hexadecimal

24

(25)

Floating-point Placeholders

25

§ %f, %e, %g – for float

— %f – displays value in a standard manner.

— %e – displays value in scientific notation.

— %g – causes printf to choose between %f and %e and to automatically remove trailing zeroes.

§ %lf – for double (the letter l, not the number 1)

(26)

Printing the value of a variable

— We can also include literal values that will appear in the output.

Ø Use two %’s to print a single percent

\n is new line

26

(27)

Output Formatting Placeholder

27

%[flags][width][.precision][length]type

§ Flags

0

- left-justify

+ generate a plus sign for positive values

# puts a leading 0 on an octal value and 0x on a hex value

pad a number with leading zeros

§ Width

— Minimum number of characters to generate

§ Precision

— Float: Round to specified decimal places

(28)

Output Formatting Placeholder

28

%[flags][width][.precision][length]type

§ Length

l long

§ Type

d, i decimal unsigned int f float

x hexadecimal o octal

% print a %

(29)

Output Formatting Placeholder

%[flags][width][.precision][length]type

§ Examples:

Format codes printf:

http://en.wikipedia.org/wiki/Printf

[ 123] [+0123] [ 0173] [ 0x7b]

[123.456000] [123.46] [ 123%]

29

(30)

Return from printf

§ A successful completion of printf returns the

number of characters printed. Consequently, for the following:

if printf() is successful,

the value in printCount should be 13.

30

(31)

Literals / Literal Constants

§ Literal – a name for a specific value

§ Literals are often called constants

§ Literals do not change value

31

(32)

Integer Constants

§ Must not contain a decimal point

§ Must not contain a comma

§ Examples

-25 68

17895

32

(33)

Integer Constants

§ May be expressed in several ways decimal number

hexadecimal number octal number

120 0x78

0170 ASCII encoded character 'x'

§ All of the above represent the 8-bit byte whose value is 01111000

33

(34)

Integer Constants

§ Constants of different representations may be intermixed in expressions:

— Examples

34

(35)

Floating Point Constants

§ Contain a decimal point.

§ Must not contain a comma

§ Can be expressed in two ways

decimal number: 23.8 4.0 scientific notation: 1.25E10

35

(36)

char Constants

36

§ Enclosed in apostrophes, single quotes

§ Examples:

'a' 'A' '$' '2' '+'

§ Format specification: %c

(37)

String Constants

37

§ Enclosed in quotes, double quotes

§ Examples:

"Hello"

"The rain in Spain"

"x"

§ Format

specification/placeholder

: %s

Note the difference between: 0, 0.0, ‘0’, "0"

(38)

Basic Data Types - Summary

Type Meaning Constants Ex. printf

int Integer value; guaranteed to contain at least 16 bits 12, -7, 0xFFE0, 0177

%i,%d, %x,

%o short int Integer value of reduced precision; guaranteed to

contain at least 16 bits

- %hi, %hx,

%ho long int Integer value of extended precision; guaranteed to

contain at least 32 bits

12L, 23l, 0xffffL

%li, %lx,

%lo long long

int

Integer value of extraextended precision; guaranteed to contain at least 64 bits

12LL, 23ll, 0xffffLL

%lli,

%llx, %llo unsigned

int

Positive integer value; can store positive values up to twice as large as an int; guaranteed to contain at least 16 bits (all bits represent the value, no sign bit)

12u, 0XFFu %u, %x, %o

unsigned short int

- %hu, %hx,

%ho unsigned

long int

12UL, 100ul, 0xffeeUL

%lu, %lx,

%lo

unsigned long long int

12ull, 0xffeeULL

%llu,

%llx, %llo

38

(39)

Basic Data Types - Summary (contd.)

Type Meaning Constants printf

float Floating-point value; a value that can contain decimal places; guaranteed to contain at least six digits of precision.

12.34f, 3.1e- 5f

%f, %e,

%g

double Extended accuracy floating-point value; guaranteed to contain at least 10 digits of precision.

12.34, 3.1e-5, %f, %e,

%g

long double

Extraextended accuracy floating-point value;

guaranteed to contain at least 10 digits of precision.

12.341, 3.1e- 5l

%Lf,

%Le, %Lg

char Single character value; on some systems, sign extension might occur when used in an expression.

'a', '\n' %c

unsigned char

Same as char, except ensures that sign extension does not occur as a result of integral promotion.

-

signed char

Same as char, except ensures that sign extension does occur as a result of integral promotion.

-

39

(40)

Terminal Input

§ We can put data into variables from the standard input device (stdin), the terminal keyboard

§ When the computer gets data from the terminal, the user is said to be acting interactively.

§ Putting data into variables from the standard input device is accomplished via the use of the scanf

function

40

(41)

§ General format

scanf(format-string, address-list)

§ Example

§ The format string contains placeholders (one per address) to be used in converting the input.

— %d – Tells scanf that the program is expecting an ASCII encoded integer number to be typed in, and that scanf should convert the string of ASCII characters to internal binary integer representation.

§ Address-list: List of memory addresses to hold the input values

Keyboard Input using scanf

& (address of operator) is required

41

(42)

Addresses in scanf()

§ Address-list must consist of addresses only

— scanf() puts the value read into the memory address

— The variable, age, is not an address; it refers to the content of the memory that was assigned to age

§ & (address of) operator causes the address of the

variable to be passed to scanf rather than the value in the variable

§ Format string should consist of a placeholder for each address in the address-list

Format codes w/scanf:

http://en.wikipedia.org/wiki/Scanf

42

(43)

Return from scanf()

§ A successful completion of scanf() returns the number of input values read. Returns EOF if hits end-of-file reading one item.

Consequently, we could have

Ø If scanf() is successful,

the value in dataCount should be 2

— Spaces or new lines separate one value from another

43

(44)

Keyboard Input using scanf

§ When using scanf for the terminal, it is best to first issue a prompt

— Waits for user input, then stores the input value in the memory space that was assigned to age.

— Note: ‘\n’ was omitted in printf

Ø Prompt ‘waits’ on same line for keyboard input.

— Including printf prompt before scanf maximizes user-friendly input/output

44

(45)

scanf Example

45

(46)

Input using scanf()

§ Instead of using scanf() twice,

we can use one scanf() to read both values.

46

(47)

Bad Data

§ scanf stops at the first bad character.

§ The value of y was never set. The value 4 is what was left in the memory location named y the last time the location was assigned a value.

47

(48)

Format Placeholder for Input

48

§ When reading data, use the following format specifiers / placeholders

%d – for integers, no octal or hexadecimal

%i – for integers allowing octal and hexadecimal

%f – for float

%lf – for double (the letter l, not the number 1)

§ Do not specify width and other special printf options

(49)

Executable Code

§ Expressions consist of legal combinations of

Ø constants

Ø variables

Ø operators

Ø function calls

49

(50)

Executable Code

50

§ Operators

— Arithmetic:

— Relational:

— Logical:

— Bitwise:

— Shift:

+, -, *, /, %

==, !=, <, <=, >, >=

!, &&, ||

&, |, ~, ^

<<, >>

§ See Expressions

— 4th Edition: p.443-450

— 3rd Edition: p. 439-445

(51)

Arithmetic

§ Rules of operator precedence (arithmetic ops):

§ Average a + b + c / 3 ?

Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are

nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*, /, or % Multiplication Division

Modulus

Evaluated second. If there are several, they are evaluated left to right.

+ or - Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

51

(52)

Precedence Example

52

§ Find the average of three variables a, b and c

Do not use:

Use:

a + b + c / 3 (a + b + c ) / 3

(53)

The Division Operator

§ Generates a result that is the same data type of the largest operand used in the operation.

§ Dividing two integers yields an integer result.

Fractional part is truncated.

5 / 2 2

17 / 5 3

ØWatch out: You will not be warned!

53

(54)

The Division Operator

54

§ Dividing one or more decimal floating-point values yields a decimal result.

5.0 / 2 2.5

4.0 / 2.0 2.0 17.0 / 5.0 3.4

(55)

The modulus operator: %

— % modulus operator returns the remainder

7 % 5 2

5 % 7 5

12 % 3 0

55

(56)

Evaluating Arithmetic Expressions

§ Calculations are done ‘one-by-one’ using

precedence, left to right within same precedence

§ 11 / 2 / 2.0 / 2 performs 3 separate divisions.

1. 11 / 2 5 2. 5 / 2.0 2.5 3. 2.5 / 2 1.25

56

(57)

Arithmetic Expressions

a/b

2x 2*x

(x-7)/(2 + 3*y)

b

math expression C expression

a

x -7 2 +3y

57

(58)

Evaluating Arithmetic Expressions

58

2 * (-3) -6

4 * 5 - 15 5

4 + 2 * 5 14

7 / 2 3

7 / 2.0 3.5

2 / 5 0

2.0 / 5.0 0.4

2 / 5 * 5 0

2.0 + 1.0 + 5 / 2 5.0

5 % 2 1

4 * 5/2 + 5 % 2 11

(59)

Data Assignment Rules

§ In C, when a floating-point value is assigned to an integer variable, the decimal portion is truncated.

§ Only integer part ‘fits’, so that’s all that goes

§ Called ‘implicit’ or ‘automatic type conversion’

59

(60)

Arithmetic Precision

60

§ Precision of Calculations

§ VERY important consideration!

§ Expressions in C might not evaluate as you ‘expect’!

§ ‘Highest-order operand’ determines type of arithmetic ‘precision’ performed

§ Common pitfall!

§ Must examine each operation

(61)

Type Casting

§ Casting for Variables

§ Can add ‘.0’ to literals to force precision arithmetic, but what about variables?

§ We can’t use ‘myInt.0’!

§ type cast – a way of changing a value of one type to a value of another type.

§ Consider the expression 1/2: In C this expression evaluates to 0 because both operands are of type integer.

61

(62)

Type Casting

1 / 2.0 gives a result of 0.5 Given the following:

result is 0, because of integer division

62

(63)

Type Casting

§ To get floating point-division, you must do a type cast from int to double (or another floating-point type), such as the following:

— This is different from (double) (m/n)

Type cast operator

63

(64)

Type Casting

64

§ Two types of casting

§ Implicit – also called ‘Automatic’

§ Done for you, automatically 17 / 5.5

This expression causes an ‘implicit type cast’ to take place, casting the 17 à 17.0

§ Explicit type conversion

§ Programmer specifies conversion with cast operator (double)17 / 5.5

(double) myInt / myDouble

(65)

Abreviated/Shortcut Assignment Operators

§ Assignment expression abbreviations

a = a + 3; can be abbreviated as a += 3;

using the addition assignment operator

§ Examples of other assignment operators include:

Assignment Shortcut d = d - 4 d -= 4 e = e * 5 e *= 5 f = f / 3 f /= 3 g = g % 9 g %= 9

65

(66)

Shorthand Operators

§ Increment & Decrement Operators

§ Just short-hand notation

§ Increment operator, ++

intVar++; is equivalent to intVar = intVar + 1;

§ Decrement operator, --

intVar--; is equivalent to intVar = intVar – 1;

66

(67)

Shorthand Operators: Two Options

§ Post-Increment x++

§ Uses current value of variable, THEN increments it

§ Pre-Increment ++x

§ Increments variable first, THEN uses new value

67

(68)

Shorthand Operators: Two Options

68

§ ‘Use’ is defined as whatever ‘context’ variable is currently in

§ No difference if ‘alone’ in statement:

x++; and ++x; à identical result

(69)

Post-Increment in Action

§ Post-Increment in Expressions:

§ This code segment produces the output:

4 3

§ Since post-increment was used

69

(70)

Pre-Increment in Action

§ Now using pre-increment:

§ This code segment produces the output:

6 3

§ Because pre-increment was used

70

(71)

Attention: Integer overflow

What happens if an integer tries to get a value too big for its type (out of range)?

#include <stdio.h>

int main(void) {

int i = 2147483647;

printf("%i %i %i\n", i, i+1, i+2);

return 0;

}

Program output:

2147483647 -2147483648 -2147483647

Explanation:

Assume int is stored on 32 bits: the first bit represents the sign, the rest of 31 bits represent the value.

Biggest positive int value here: 231-1 = 2147483647 71

(72)

Attention: Floating point round-off error

#include <stdio.h>

int main(void) {

float a,b;

b = 2.0e20 + 1.0;

a = b - 2.0e20;

printf("%f \n", a);

return 0;

}

Program output:

4008175468544.000000

Explanation: the computer doesn't keep track of enough decimal places ! The number 2.0e20 is 2 followed by 20 zeros and by adding 1

you are trying to change the 21st digit. To do this correctly, the program would need to be able to store a 21-digit number. A float number is typically just six or seven digits scaled to bigger or smaller numbers with an

exponent.

72

(73)

73

T H E E N D

Chapter 3

Variables and Expressions

References

Related documents

The activity described below aims to teach high-intermediate and advanced learners of English how to understand American housing ads.. The main target group is members of the

Values of truth, honesty and trustworthiness; Hono(u)rable ethical practice; Safety , health and welfare of the public; Protection of the environment; Promotion of health, safety

The Navy Warfare Development Command Operations Security (OPSEC) instruction number NTTP 3-54M/MCWP 3-40.9, the NAVSUP Husbanding and Ordering Officer Guide, the NAVSUP

Constant value reside in variables declared variable and declares a variable is expected result you declare something new variable determines where different.. This variable for

The following table shows the effect of various flow rate of makeup benzene on dry natural gas water content, regenerated MEG mass fraction, regenerated MEG

Distributional requirements for the sophomore year Students must have enrolled for at least one course credit in each of the three disciplinary areas and for at least one course

knowing what terms are in the top position in Google, and being able to quantify their value through cold, hard data will go a long way in understanding the true value of those

He reported a high and positive (0.77 to 0.98) genetic correlations between body weight at different ages from dam and sire plus dam components of variance; and the