Title: Variable Rules
1Variable Rules
Ch 3 Variables and Arithmetic Operations
- Must declare all variable names
- List name and type
- Keep length to 31 characters
- Older compiler restriction
- Give numeric values to variables with assignment
statement
2Naming Identifiers
- First character must be letter
- Other characters may be letters (a-z, A-Z, _ ) or
digits 0-9 - Cannot use C keywords (reserved words see
next page) - Cannot have blanks within identifiers
- Use descriptive names (Ex Area_Of_Circle
instead of x)
Examples Valid Identifiers
Examples Invalid Identifiers
3Keywords
- Invalid names for identifiers
- Reserved words with special meaning to C
4Declaring Variables
- Variables MUST be declared
- List name and data type.
- Data types include int, float, double, char,
(more details later) - Variables of same type may be declared in same
statement (separate by comma). - Causes C compiler to know size of space to be
reserved for storing variables value
Examples
5Assignment Statements
- Form variable_name value or expression
- Single variable name MUST appear on left.
- Expression on the right may contain numbers,
operators, and functions. Examples - A 2
- B A 10cos(alpha)
Examples (Valid Assignments)
Examples (Invalid Assignments)
6Assignment Statements
- It is possible to assign values to more than one
variable at a time as follows - Example a b c 36
- Equal sign is assignment operator
- Note be careful does NOT mean equal (as in a
math course) - Example x x 2 means xnew xold 2
Example Determine the value of x that is
displayed. x 3 x x 2 x xx-2x4 x
xxxx cout ltlt x ltlt x
7C data typesVariables are typically assigned a
data type.Example int x //integer data
type double y //real number (floating point)
data typeThere are several data types available
in C
- There are several data types available in C,
including - Integers (including int, short int, long int,
unsigned int, etc.) - Real numbers (including float, double, and long
double) - Characters (char)
- Boolean (bool)
- Strings (string) - using the string class,
string.h - More details to follow on data types
8Integer data typesIntegers are numbers without
decimal points.Exceeding the range may yield
unexpected results as values cycle through the
range (see discussion in text).
Some compilers, including ours, use 4 bytes
for int variables.
Examples
9Real data typesReal numbers are numbers with
decimal points.They may be in scientific
notation or in fixed-point notation.Exceeding
the range may yield overflow or underflow
errors.
Examples (include examples in scientific
notation)
10Character Data Type (char)
- A character consists of any single symbol
enclosed in single quotes - Escape sequences (such as \t, \n, \r, \v) are
regarded as a single character - C actually assigns the ASCII code (see Table
3.5 on next page) for the character, so you can
think of a character as essentially acting like
an integer - Example
- char c1 ?
- char Middle_Initial W
Additional Examples
11Example The following two commands have the same
effect char c1 A char c1
65 Additional Examples
12Symbolic Constants
- Symbolic constant Constant value that is
declared with an identifier using the const
keyword - A constants value may not be changed
- Example const int MAXNUM 100
- Constants are useful for fixed values, limits on
arrays, protecting inputs to functions, etc. We
will see some of these uses later in the course.
Example int main() const int MAXROWSIZE
50 // max array size const double G 32.2
// acceleration due to gravity const Q
-1.6022e-19 // charge on
electron const double TAXRATE 0.05 //VA
state sales tax int a,b,c,d double x,y,z
13Symbolic Constants
- Good programming places statements in appropriate
order
- Proper placement of statements
- preprocessor directives
- int main()
- symbolic constants
- main function declarations
- other executable statements
- return value
-
14Arithmetic Operations
- Look like algebraic expressions
- Expression consists of sequence of operand(s) and
operator(s) - Operand (variable, constant, any value)
- Most common operators (, - , , / , )
Example (describe the output of the program
below) int a, b, c, d a 4 b 2 c
(ab)/(a-b) // algebraic expression d
ab-a/b // algebraic expression cout ltlt c
ltlt c ltlt endl cout ltlt d ltlt d ltlt endl
15Common Operators for Arithmetic Operations
- i/j and ij are undefined for j 0
- Discuss operator overloading
- Example What value is assigned to x in each
case? - x 73
- x 37
- x 77
16Mixed-type Operations- Avoid unless necessary
or intentional- Form Result (Operand 1)
Operator (Operand 2)
- Notes
- If a real result is converted to an integer, it
is truncated (chopped off after the decimal
point, not rounded off). - If a real value is assigned to an integer
variable, it is truncated. - If an integer value is assigned to a real
variable, it is promoted to a real (decimal point
added).
17Mixed-type operations
Example What is the result of each operation
below? 18/4/3 18/4/3. 18/4./3 18./4/3
Example What value is assigned to each variable
below? int I1, I2 double D1, D2 I1 6.9 D1
4 I2 14/5.0 D2 14/5
18Operator PrecedenceKey Rule Evaluate
multiplication and division before addition and
subtraction.
Example Evaluate each expression below a
12/243 b 12/(24)3 c 2064 d 4-3
19Increment and decrement operators
- is the increment operator. - - is the
decrement operator. - x means x x 1
- x- - means x x 1
- When used with assignment
- When placed in front, incrementing or
decrementing occurs BEFORE value assigned - When placed in back, occurs AFTER value assigned
Example Evaluate each expression below int a
3, b 4, c 5, d 6 int e, f, g,
h a b-- e c f c g d-- h
--d
20Arithmetic Operators Table 3.8 in the text
provides a more complete list of arithmetic
operators and operator precedence.
21Compound Assignment Operators (Shortcut
Operators) Several shortcut operators are
available in C. The examples below explain how
the operators function.
Example Evaluate each expression below int a
2, b 3, c 4, d 5, e 6 a 3 b
-3 c 3 d / 3 e 3
22Math Functions
- Need cmath or cstlib headers
- include ltcmathgt or include ltcstlibgt
- Note what type and form parameters take
- Trig functions use radians not degrees
- Table 3.11 lists math library functions
- Note that
- so this is implemented in C as
- y pow(x,1.0/3.0)
23Math Functions
Example using functions from cmath
Sample Program Output This program will
calculate the area of a circle Enter the radius
of the circle 20 The area of the circle is
1256.64 Press any key to continue . . .
24Math Functions
Example Write C expressions corresponding to
each of the mathematical expressions below.
25Formatting Output
- Output values are formatted in C by inserting
I/O manipulators (parameterized) into cout
statements for printing - Example cout ltlt setprecision(6) ltlt x ltlt y
- Usually affects all outputs from that point on
(no need to include in every cout statement), but
might be compiler dependent. setw(n) only
affects the next output. - We must include the header iomanip as follows
include ltiomanipgt - Basic form cout ltlt manipulator(parameter)
- The table below lists several common I/O
manipulators
I/O Manipulator
26setw( )
- Sets field width
- Unlike most iomanipulators, setw() only affects
the next output variable. - Right justifies contents (default)
- C automatically expands if set width too small
- Form cout ltlt setw(N) // for a field
width of N
Example int num 5 cout ltlt number ltlt
setw(7) ltlt num ltlt endl
27setprecision( )
- Sets the number of significant digits. (But may
set the number of digits after the decimal point
if fixed or scientific is also used.) - Does not show trailing zeros (unless showpoint is
also used). - All digits retained in memory.
- Form cout ltlt setprecision(N) //to show N
significant digits.
Example float x 421.0, y 0.0123456789
cout ltlt setprecision(2) ltlt " x " ltlt x ltlt "\ty
" ltlt y ltlt endl cout ltlt setprecision(6) ltlt " x
" ltlt x ltlt "\ty " ltlt y ltlt endl
Output x 4.2e002 y 0.012 x 421
y 0.0123457
28setfill( )
- Specifies character for blank space in field
- Single quotes required around character enclosed
in parentheses - Form cout ltlt setfill(symbol) // to use
symbol instead of blanks
Example double num 5.34 cout ltlt setw(10) ltlt
setfill() ltlt num
Output 5.34
29setiosflags(ios )
- Performs a number of different actions based on
the flag that is set - Forms cout ltlt setiosflags(ios flag) // text
shows this form - cout ltlt flag
// might be compiler dependent - Flags include
- left left justify the output
- right right justify the output
- fixed use fixed-point notation (not scientific
notation) - scientific use scientific notation
- showpoint show trailing zeros
- noshowpoint do not show trailing zeros
- showpos include a sign with positive numbers
- Table 3.3 has a more complete list of flags
- Examples on next page
30showpoint
- Directs the output to include trailing zeros.
- Typically used with setprecision( ).
- Form cout ltlt showpoint
Example float x 421.0, y 0.0123456789
cout ltlt setprecision(2) ltlt showpoint ltlt " x "
ltlt x ltlt "\ty " ltlt y ltlt endl cout ltlt
setprecision(6) ltlt " x " ltlt x ltlt "\ty " ltlt y
ltlt endl
Output x 4.2e002 y 0.012 x 421.000
y 0.0123457
31Example double num 5.34 cout ltlt left ltlt
setfill('') ltlt setw(10) ltlt num ltlt endl
Output 5.34 (note that the output
is left justified)
Example float x 421.0, y 0.0123456789 cout
ltlt setprecision(2) ltlt scientific ltlt " x
" ltlt x ltlt "\ty " ltlt y ltlt endl cout ltlt
setprecision(6) ltlt " x " ltlt x ltlt "\ty " ltlt y
ltlt endl
Output x 4.21e002 y 1.23e-002 x
4.210000e002 y 1.234568e-002
32Printing Monetary Values
- It is necessary to use I/O manipulators to print
properly formatted monetary values.
Example double income 7842 cout ltlt
setprecision(2) ltlt fixed ltlt showpoint ltlt
"Income ltlt income ltlt endl
Output Income 7842.00
33Casting (or Type Casting)
- Cast operator A unary operator that forces the
data to the desired data type. - Cast operators include int(), float(),
double(), short(), etc. - Compile-time cast
- Syntax dataType (expression)
- Example int(ab)
Example Determine the output below. double
a,b,x,y 3.9 int c2, d3 x int(y)
a c/d b c/float(d) cout ltlt x
" ltlt x ltlt "\na cout ltlt a ltlt "\nb " ltlt b
ltlt endl
Output x a b