Title: Variables
1Variables
- Names are made up of letters and digits
- First character must be a letter
- underscore _ counts as a letter
- Upper case and lower case letters are distinct,
so a and A are two different variable names, so
as Tom and tom - Traditionally, lower case for variable names, and
all upper case for symbolic constants - You cannot use keywords as variable names
- Use meaningful variable names
- use count, instead of x for counting
- use year, instead of y for keeping track of
the year
2Variable names and keywords
- More examples on meaningful variable names
- Sum, Total_amount, radius, Room801, average,
standard_dev, StandardDev, Std - Examples of illegal variable names
- price, 1stclass, day of the year, int
- Keyword-reserved identifiers
- auto, break, case, char, const, continue,
default, do, double, else, enum, extern, float,
for, goto, if, int, long, register, return,
short, signed, sizeof, static, struct, switch,
typedef, union, unsigned, void, volatile, while
3Data types and their limitations
- char a single byte, capable of holding one
character, we usually refer to ASCII character
set (127 char) - int an integer. For our system, an integer uses
4 bytes, therefore, it has a range of -2G, 2G-1 - float floating point (single-precision), uses 4
bytes and therefore has a range of 10e-38 to
10e38 - double floating point (double-precision) 8
bytes from 10e-308 10e308 - qualifiers short, long, signed, unsigned
- For their usages, refer to any C Manual or
References. - In this class, we seldom use the above qualifiers.
4Declarations
- All variables must be declared before use
- A declaration specifies a type
- int lower
- char c
- float total_cost
- int lower, upper
- A variable may also be initialized in its
declaration - int lower 0
- char esc \\
- float total_cost 2000.0
- For constant, the qualifier const can be
applied to the declaration of any variable to
specify that its value will not be changed - const double PI 3.141592653548979
- const double e 2.71828182845905
5Assignment statement
- Assigning a value or an expression to a variable
- a 5 / assign a value 5 to variable a /
- 5 a lt-- Wrong (syntax error), you cannot
assign anything to a number - Be careful about the R.H.S and the L.H.S
- int a 5 int a 5
- int b 10 int b 10
- a b b a
- The results are different!!
- Swapping the values between two variables
- int a 5 int a 5
- int b 10 int b 10
- int temp
- temp a a a b
- a b b a - b
- b temp a a - b
6Arithmetic Operators - / (modulus)
- Integer division truncates any fractional part
- The operator cannot be applied to float or
double - int x 27 int x 28
- int y 4 int y 4
- int result int result
- result x / y gt 6 result x / y gt 7
- result x y gt 3 result x y gt 0
- Precedence (unary) , - ---gt , /, ---gt
,- - Precedence and associativity of operators (as
Table 2-1) - (fahr - 32) 5 / 9 (fahr - 32) / 9 5
- 20 20
- -12 -12
- -60 -1
- -6 -5
7Be Careful on Integer Division!
- 25 / 2 2 gt 24
- 25.0 / 2 2 gt 25.000000
- t t / 2 not equal to t t / 2.0 (if t is odd)
- Float to integer is by truncation, not by
round-off - int x 27 int x 27 int x 27
- int y 4 int y 4 float y 4.0
- int result float result float result
- result x / y result x / y result x / y
- result is 6 result is 6.00 result is 6.75
8- Relational Operators gt, gt, lt, lt, , !
- Relational operators have lower precedence than
arithmetic operators. For example, - i lt lim - 1 lt---gt i lt (lim - 1)
- Logical Operators ,
- Expressions connected by or are evaluated
left to right, and evaluation stops as soon as
the truth or falsehood of the result is known - The precedence of is higher than that of ,
and both are lower than relational and equality
operators - By definition, the numeric value of a relational
or logical expression is 1 if the relation is
true, and 0 if false - The unary negation operator ! converts a
non-zero operand into 0, and a zero operand into 1
9Relational and Logical Operators (examples)
- int i 10 int i 1, j 2, k 3
- int j int x
- j i gt 5 x i lt 0 j gt 2
- j i lt 10 x i gt 0 j gt 2
- j i lt 10 x i lt 0 j gt 2
- j i 1 lt 10 x i gt 0 j gt 2
- float p 10.0 x (i gt 0) (j gt 2)
- float q 5.0 x (i gt 0) (j gt 2) (k
3) - j p gt 0.0 x (i gt 0) (j gt 2) (k 3)
- j p lt 0.0 A B (AB)(AB)!A !(AB) !AB
- j 0.0 lt p - q T T T T F F F
- j i 10 T F F T F T F
- j i 1 ! 10 F T F T T T T
- j i ! 10 1 F F F F T T F
10Type Conversions (Basic Conversion in C)
- main()
-
- float f1 123.456, f2
- int i1, i2 -150
- char c a
- i1 f1 / i1 123 /
- f1 i2 / f1 -150.000000 /
- f1 i2 / 100 / f1 -1.000000 /
- f2 i2 / 100.0 / f2 -1.500000 /
- i1 5
- i1 10
- printf(d, i1) / i1 10 /
- i1 i1 6
- printf(d, i1) / i1 16 /
11Increment and Decrement Operators
- i i 1 can be written as i or i
- In both cases, the effect is to increment
variable i - i increments i after its value has been used
- i increments i before its valie is used
- Why and what is the difference?
- int i 5, x int i 5, x
- x i x i
- printf(xd id\n, x, i) printf(xd
id\n, x, i) - Program output
- x5 i6 x6 i6
- Short-cut of
- x i gt x i x i gt i i 1
- i i 1 x i
12Assignment Operators and Expressions
- Assignment operators , -, , /, , ...
- expression1 (expression1) operator
(expression2) can be written as expression1
operator expression2 - i i 2 can be written as i 2
- stock - 100 is equivalent to
- stock stock - 100
- Be careful, x y 1 means x x (y 1)
not x x y 1 - Why I dont like it
- sum count gt sum count gt sum sum
count - count count 1 count
count 1 - How about sum count ?
13Control Flow
- Statements and Blocks
- An expression such as x 0 or i or printf(...)
becomes a statement when it is followed by a
semi-colon - In C, the semi-colon is a statement terminator
- Braces and are used to group declarations and
statements together into a compound statement, or
block, so that they are syntactically equivalent
to a single statement - No semi-colon after that ends a block
- Statement statement or
-
statement1 -
statement2 . . . -
statementN -
14The IF Statement
- if (expression) statement1
- if (expression) statement1 else statement2
- The expression is evaluated If it is true,
statement1 is executed - If the expression is false, and if there is an
else part, statement2 is executed - If the IF statement is simply testing the numeric
value of an expression, you can simplify the
syntax - if (expression ! 0)
- becomes
- if (expression)
- IF statements can be nested That means there is
an IF statement inside an IF statement
15A Simple Program on IF statements
- include ltstdio.hgt if (tall)
- main() if (heavy)
- printf(football player)
- int sex, height, weight else
- int tall, heavy printf(basket ball
player) - ..... else
- if (sex 1) if (heavy)
- printf(TV watcher)
- printf(He can be a ) else
- if (height gt 175) printf(ice skater)
- tall 1
- else
- tall 0
- if (weight gt 200)
- heavy 1
- else
- heavy 0
16More on IF statements
- if (!heavy) printf(ice skater)
- else printf(TV watcher)
- is the same as
- if (heavy) printf(TV watcher)
- else printf(ice skater)
- Ambiguity in an IF statement
- if (n gt 0) if (n gt 0)
- if (a gt b) if (a gt b)
- z a z a
- else else
- z b z b
- Associating the else with the closest previous
else-less IF statement - If that is not you want, braces must be used
17Nested IF statements
- include ltstdio.hgt
- main()
-
- int score
- printf(Please type in your score)
- scanf(d, score)
- printf(Your grade is a )
- if (score gt 90) printfA)
- else
- if (score gt 80) printf(B)
- else
- if (score gt70) printf(C)
- else
- if (score gt50) printf(D)
- else
- if (score gt 40) printf(D)
- else
- printf(F)
18Switch Statement
- switch (expression)
- case const-expr1 statements1
- case const-expr2 statements2
- .....
- case const-exprN statementsN
- default statements(N1)
-
- The switch statement is a multi-way decision that
test whether an expression matches one of a
number of constant integer values, and branches
accordingly - default is executed if there is no match
- default is optional
- The break statement causes an immediate exit from
the switch statement
19switch VS. if
- Try to write a program that print the name of the
operation for that operator - if (op ) printf(addition)
- else if (op -) printf(subtraction)
- else if (op ) printf(multiplicat
ion) - else if (op /)
printf(division) - else if (op )
printf(mod... - when there are more operators like, !, , you
can run outof space, and have to type on the next
line. But for the switch statement, we can have - switch(op)
- case printf(addition) break
- case - printf(subtraction) break
- case printf(multiplication) break
- ...
- default break
-
20The break Statement inside switch
- int num_count 0, num_char 0
- char ch
- while ((ch getchar()) ! EOF)
- switch (ch)
- case 1
- case 2
- case 3
- case 4
- ...
- case 9
- case 0 num_count
- default num_char
- break
-
21Loops---while statement
- Statement structure
- while (expression)
- statements
- As mentioned in the previous lectures,
- statementsgt statement or
- statement1
- statement2
- ...
- statementN
-
- The expression is evaluated
- If the expression is true (non-zero), the
statements are executed and expression is
re-evaluated - Until the expression return false (becomes zero),
at this point, the execution get out of the while
loop - You can use the break statement to jump out of
the loop - In general, frequent use of the break statement
is bad programming
22Examples on while Statement
- int i 0
- while (i lt 9)
- printf(i d\n, i)
- i
-
- char ch
- ch getchar()
- while (ch ! EOF)
- if (ch 4) break
- ch getchar()
-
- if (ch 4)
- printf(Bad number\n)
- else
- printf(Good number\n)
- Beware of infinite loops!!!
23Loops---for statement
- Statement structure
- for (expr1 expr2 expr3)
- statements
- equivalent to
- expr1
- while (expr2)
- statements
- expr3
-
- expr2 is evaluated
- If expr2 is true, the statements and expr3 are
executed and expr2 is re-evaluated - Until expr2 becomes false, then the execution
will jump out of the for loop - You can use the break statement to jump out of
the loop - Using a break statement to jump out from a for
loop is a very bad practice in programming!
24Examples on for statement
- int i int i
- i 0 for (i 0 i lt 9 i)
- while (i lt 9) printf(i d\n, i)
- printf(i d\n, i)
- i
-
- The for statements structure can be viewed as
- for (initialize-loop-index condition
incremental-steps) - statement-body
- initialize-loop-index and incremental-steps are
usually assignments or function calls - condition is usually a relational expression
- Any of the three parts can be omitted, but the
semi-colons must remain - If expr2 (condition) is omitted, it is
permanently true - The code for ( ) ... refers to an infinite
loop! You will need a break statement to get out
of it
25Loops---do while statement
- Statement structure
- do
- statements
- while (expression)
- The do while statement is almost like a while
statement - while the while and for loops test the
termination condition at the top, the do while
statement test the condition at the bottom after
executing the statements at least once - Two examples keeping track of the number of
char being read - int n int n
- char ch char ch
- n 0 n 0
- while ((ch getchar()) ! ) do
- n ch getchar()
- n
- while (ch ! )
26Nested Loops
- Nested loops means loops inside a loop
- int i, j int i, j
- for (i 1 i lt 10 i) i 1
- printf(3d, i) while (i lt 10)
- for (j 1 j lt 10 j) printf(3d,
i) - printf(3d, ij) j 1
- while (j lt 10)
- printf(\n) printf(3d,ij)
- j
-
- printf(\n)
- i
-
- Program output
- 1 1 2 3 4 5 6 7 8 9
- 2 2 4 6 8 10 12 14 16 18
- 3 3 6 9 12 15 18 21 24 27
- 4 8 12 ....................
27A program called dice.c
include ltstdio.hgt main() int count 0 int
overall 0 int i, j, k, n n 7 for (i
1 i lt 6 i) for (j 1 j lt 6 j)
for (k 1 k lt 6 k) if (i
j k n) count
printf("3d3d3d\n", i, j, k)
overall
printf("\nCount d", count) printf("\nPercentag
e f\n", count 100.0 / overall)
1 1 5 1 2 4 1 3 3 1 4 2 1 5
1 2 1 4 2 2 3 2 3 2 2 4 1 3 1
3 3 2 2 3 3 1 4 1 2 4 2 1 5 1
1 Count 15 Percentage 6.944444
28A Word on the break Statement
- The break statement provides an early exit from
for, while , do-while and switch statements - A break causes the innermost enclosing loop or
switch to be exited immediately - Commands and Sections not recommended to be used
- The continue statement. (section 3.7) page 64-65
- Not a natural way to test for a condition
- The goto and labels. (section 3.8) page 65-66
- Produced spaghetti codes.
29Arrays
- The declaration int a10 defines an array a of
size 10 - a10 represents a block of 10 consecutive object
named a0, a1, a2, ... a9 - a0 a1 a2 .....
- a10 declares a to be an array of 10 integers
- Array subscripts always starts at zero in C
- A subscript can be any integer expression, which
includes integer variables like i, and integer
constants - The notation ai refers to the i-th element of
the array - Each element is to be treated as a variable of
the defined type ai is an integer variable
30A Program on Counting Digits
- include ltstdio.hgt
- main()
-
- char c
- int i, num_digit10
- for (i 0 i lt 10 i)
- num_digiti 0
- while ((c getchar()) ! EOF)
- switch (c)
- case 0 case 1 case 2 case 3
case 4 - case 5 case 6 case 7 case 8
case 9 - num_digitc - 0
- break
- default break
-
-
- printf(Distribution among the digits \n)
- for (i 0 i lt 10 i)
- printf(num_digitd 3d\n, i,
num_digiti)
31A program on Binary Search
- include ltstdio.hgt
- main()
-
- int x, n, a100, low, high, mid, found
- / find x in array a a0lta1lt...lta99
- assume we filled array a with values /
- n 100 / number of elements /
- x 37 / the number to be found /
- low 0
- high n - 1
- found 0
- while ((low lt high) (!found)) while (low
lt high) - mid (lowhigh) / 2 mid
(lowhigh) / 2 - if ( x lt amid) if (x lt amid)
- high mid -1 high mid -
1 - else if (x gt amid) else if (x gt
amid) - low mid 1 low
mid 1 - else else
- found 1 found
1
32Multi-dimensional Arrays
- The declaration int A520 declares a
two-dimensional array A with 5 rows by 20 columns - The variable Axy represents the element in
the x-th row and y-th column in the array A - Two-dimensional arrays can represents
- Your appointment schedule --- int
schedule247 - Two-dimensional matrix --- int matrix_A33
- When you declare an array, like a variable, you
have to initialize it - You cannot assume any value when you declare an
array, you have to initialize it. - int a100, i
- for (i 0 i lt 100 i) ai 0
- You can define the array of any type, not just
integer, but floating point or character or
others - An array of char is also called string