Title: Variables
1Basic C Programming
Review
- Variables
- and
- Special Chars
- (Ch. 2, 3)
2Valid Variable Names
- Rules for variable names in C (page 33)
- The first character must be an alphabetic
character or underscore - Consists only of alpha-numeric and underscore
characters - Cannot duplicate a reserved word (see Appendix B)
Invalid Names a for 2name a
a int
Valid Names a PI student_name
_PI _assign1
3Important Special Characters
As a Character In a String
- Return \n
- Null
- Single Quote
- Double Quote
- Backslash
\n \0 \ \ \\
\n \ \\
4Constant declarations
- Constants are used to store values that never
change during the program execution. - Using constants makes programs more readable and
maintainable. - Syntax
- const lttypegt ltidentifiergt ltexpressiongt
- Examples
- const double US2HK 7.8
- //Exchange rate of US to HK
- const double HK2TW 3.98
- //Exchange rate of HK to TW
- const double US2TW US2HK HK2TW
- //Exchange rate of US to TW
5Variable declarations
- Variables are used to store values that can be
changed during the program execution. - A variable is best thought of as a container for
a particular type of data/value. - You must specify the variables type when you
declare it - Syntax
- lt type gt lt identifier gt
- lt type gt lt identifier gt lt expression gt
- Examples
- int sum
- int i j 0
- int total 3445
- char answer 'y'
- double temperature -3.14
6Variable declarations
- Variables are not automatically initialized. For
example, after declaration - int sum
- the value of the variable sum can be anything
(garbage). - Thus, it is good practice to initialize variables
when they are declared. - A variable has a type and it can contain only
values of that type. For example, a variable of
the type int can only hold integer values. - Once a value has been placed in a variable it
stays there until the program deliberately alters
it. -
7Character data
- A variable or a constant of char type can hold an
ASCII character (see Appendix A of the textbook).
- When initializing a constant or a variable of
char type, or when changing the value of a
variable of char type, the value is enclosed in
single quotation marks. -
- Examples
- const char star ''
- char letter, one '1'
8Programming
9The Basic if Statement
- Syntax
- if(Expression)
- Action
- If the Expression is true then execute Action
- Action is either a single statement or a group of
statements within braces
10Choice (if)
- Example find the absolute value
- if (value lt 0)
- value -value
- Can put multiple action statements within braces
- if ltit's raininggt
- lttake umbrellagt
- ltwear raincoatgt
11Sorting Two Numbers
int value1 int value2 int temp cout ltlt "Enter
two integers " cin gtgt value1 gtgt
value2 if(value1 gt value2) temp
value1 value1 value2 value2 temp cout
ltlt "The input in sorted order " ltlt value1
ltlt " " ltlt value2 ltlt endl
12Relational Operators
- Relational operators are used to compare two
values - Math C Plain English
- equals example if(ab)
- BUT (ab) means put the value of b into a
- lt lt less than
- ? lt less than or equal to
- gt gt greater than
- ? gt greater than or equal to
- ? ! not equal to
13A Boolean Type
- C contains a type named bool which can have one
of two values - true (corresponds to non-zero value)
- false (corresponds to zero value)
- Boolean operators can be used to form more
complex conditional expressions - The AND operator is
- The OR operator is
- The NOT operator is !
- Warning
- and are bitmap operators
14More Operator Precedence
- Precedence of operators (from highest to lowest)
- Parentheses ( )
- Unary operators !
- Multiplicative operators /
- Additive operators -
- Relational ordering lt lt gt gt
- Relational equality !
- Logical and
- Logical or
- Assignment
15Examples of bool
- Assignments to bool type variables
- bool P truebool Q falsebool R
truebool S P Q // Fbool T !Q R //
T bool U !(R !Q) // F
16Operator Precedence Examples
- Examples
- 5 ! 6 7 lt 3
- is equivalent to
- (5 !6) (7 lt 3)
- 5 15 4 13 12 lt 19 !false 5 lt 24
- is TRUE
17The if-else Statement
Syntax if (Expression) Action1 else
Action2 ? If Expression is true then execute
Action1 otherwise execute Action2
18The if-else Statement
- if ltit's sunnygt
- ltgo to beach with sun blockgt
-
- else
- lttake umbrellagt
19Finding the Big One
int value1 int value2 int larger cout ltlt
"Enter two integers " cin gtgt value1 gtgt
value2 if (value1 gt value2) larger
value1 else larger value2 cout ltlt "Larger
is " ltlt larger ltlt endl
20if-else-if Statements
F
T
F
T
F
T
F
T
21if-else-if Statements
- if ltMon, Wedgt
- ltgoto COMP 103gt
-
- else if ltTuegt
- ltgoto Labgt
-
- else if lt12noon or 7PMgt
- lteatgt
-
- else
- ltsleepgt
22if-else-if Statement
- if(score gt 90)
- cout ltlt "Grade A" ltlt endl
- else if(score gt 80)
- cout ltlt "Grade B" ltlt endl
- else if(score gt 70)
- cout ltlt "Grade C" ltlt endl
- else if(score gt 60)
- cout ltlt "Grade D" ltlt endl
- else
- cout ltlt "Grade F" ltlt endl
23switch Statement
- Equivalent to the previous if-else-if
- switch(score/10)
- case 10
- case 9 cout ltlt "Grade A" ltlt endl
- break
- case 8 cout ltlt "Grade B" ltlt endl
- break
- case 7 cout ltlt "Grade C" ltlt endl
- break
- case 6 cout ltlt "Grade D" ltlt endl
- break
- default cout ltlt "Grade F" ltlt endl
24Nested if Statements
- Nested means that one complete statement is
inside another - if ltit's Mondaygt
- if ltit's 100pmgt
- if ltit's raininggt
- ltbring umbrellagt
-
- ltgo to COMP 103gt
-
- ltcall your friendsgt
25Dangling Else Problem
- What is the value of c after the following is
executed? - int a-1, b1, c1
- if(agt0)
- if(bgt0)
- c 2
- else
- c 3
- C groups a dangling else with the most recent
if (answer c1).
26Programming
27Advantages of Functions
- A complex problem is often easier to solve by
dividing it into several smaller parts, each of
which can be solved by itself. - These parts are called functions in C
- Functions make programs easier to understand.
- Functions make programs easier to modify.
- Functions can be called several times in the same
program, allowing the code to be reused.
28Function Input and Output
29Functions in a Program
- C programs usually have the following form
- // include statements
- // function prototypes
- // main() function
- // user-defined functions
30Function Prototype
- The function prototype declares the interface, or
input and output parameters of the function,
leaving the implementation for the function
definition. - The function prototype has the following syntax
- lttypegt ltfunction namegt(lttype listgt)
- Example A function that prints the card (J)
given the card number (11) as input - void printcard(int num)
- (This is a void function - a function that does
not return a value)
31Function Definition
- The function definition can be placed anywhere in
the program after the function prototypes. - You can place a function definition in front of
main(). In this case there is no need to provide
a function prototype for the function, since the
function is already defined before its use. - A function definition has following syntax
- lttypegt ltfunction namegt(ltparameter listgt)
- ltlocal declarationsgt
- ltsequence of statementsgt
-
32Function Call
- A function call has the following syntax
- ltfunction namegt(ltparameter listgt)
- There is a one-to-one correspondence between the
parameters in a function call and the parameters
in the function definition.
33Printing Cards (void function)
- The main() program which calls printcard()
- include ltiostreamgt
- using namespace std
- void printcard(int) // function prototype
- int main()
- int c1, c2, c3, c4, c5
- // pick cards
- . . .
- // print cards
- printcard(c1)
- printcard(c2)
- printcard(c3)
- printcard(c4)
- printcard(c5)
- // find score
- // print score
34Printing Cards
- A function that prints the card (J) given the
card number (11) as input - void printcard(int cardnum)
- if(cardnum1)
- cout ltlt "A"
- else if(cardnumgt2 cardnumlt10)
- cout ltlt cardnum
- else if(cardnum11)
- cout ltlt "J"
- else if(cardnum12)
- cout ltlt "Q"
- else if(cardnum13)
- cout ltlt "K"
35Absolute Value (returns int)
- include ltiostreamgt
- int absolute(int x) // function prototype
- int main()
- int x, y, diff
- cout ltlt "Enter two integers "
- cin gtgt x gtgt y
- diff absolute(x - y)
- cout ltlt "The absolute diff is " ltlt diff ltlt
endl - return 0
-
- // Define a function to take absolute value of an
int - int absolute(int x)
- if (x gt 0) return x
- else return -x
-
36Passing Parameters by Value
- A function returns a single result (assuming the
function is not a void function) - One of the statements in the function body should
have the form - return ltexpressiongt
- The value passed back by return should have the
same type as the function.
37Pass by Value
- Different location in memory
- Changes to the parameters inside the function
body have no effect outside of the function.
38Pass by Value Example 1
- For example, consider the following code
- int sum(int a, int b)
- a a b
- return a
-
- void main()
- int x, y, z
- x 3 y 5
- z sum(x,y)
-
- What is the value of x, y, and z at the end of
the main() program?
39Pass by Value Example 1
- The answer 3, 5, and 8. (x,y,z)
- Even though the value of parameter a is changed,
the corresponding value in variable x does not
change. - This is why this is called pass by value.
- The value of the original variable is copied to
the parameter, but changes to the value of the
parameter do not affect the original variable. - In fact, all information in local variables
declared within the function will be lost when
the function terminates. - The only information saved from a pass by value
function is in the return statement.
40Pass by Value Example 2
- void Increment(int Number)
- Number Number 1
- cout ltlt "Number " ltlt Number ltlt endl
-
- void main()
- int I 10
-
- cout ltlt "I is " ltlt I ltlt endl
- Increment(I)
-
- cout ltlt "I is " ltlt I ltlt endl
41Passing Parameters by Reference
- To have a function with multiple outputs, we have
to use pass by reference. - Reference (address) of parameter is passed to the
function, instead of its value. - If the function changes the parameter value, the
changes will be reflected in the program calling
it. - How to pass parameters by reference
- lttypegt ltvariablegt, ... , lttypegt ltvariablegt
42Pass by Reference Example
- The correct implementation of the Increment
function - include ltiostreamgt
- using namespace std
- void Increment(int Number)
- Number Number 1
- cout ltlt "Number " ltlt Number ltlt endl // 11
-
- void main()
- int I 10
- Increment(I)
- cout ltlt "I is " ltlt I ltlt endl // 11
-
- Pass-by-Reference-1.cpp
43Example Exchange two numbers
If we use pass by value, it will not work!!!
- a and num1 are in the same location in memory
- Also b and num2
44Pass by value and by reference
45Programming
46Iterative Constructs
- Provide
- Ability to control how many times a statement
list is executed - Three constructs
- while statement
- for statement
- do-while statement
47The while Statement
- Syntax
- while (Expression)
- Action
- How it works
- If Expression is true then execute Action
- Repeat this process until Expression evaluates to
false - Action is either a single statement or a group of
statements within braces
48Example N! (while)
- int number, factorial, n
- cout ltlt "Enter number "
- cin gtgt number
- factorial 1
- n 1
- while(n lt number)
- factorial n
- n
-
- cout ltlt "The factorial of " ltlt number
- ltlt " is " ltlt factorial ltlt endl
49The for Statement
- Syntax
- for (ForInit ForExpression PostExpression)
- Action
- How it works
- Execute ForInit statement
- As long as ForExpression
- is true
- Execute Action
- Execute PostExpression
50Example N! (for)
- int number, factorial, n
- cout ltlt "Enter number "
- cin gtgt number
- factorial 1
- for (n1 nltnumber n)
- factorial n
- cout ltlt "The factorial of " ltlt number
- ltlt " is " ltlt factorial ltlt endl
51The Do-While Statement
- Syntax
- do Action
- while (Expression)
- How it works
- Execute Action
- if Expression is true then execute Action again
- Repeat this process until Expression evaluates to
false - Action is either a single statement or a group of
statements within braces
52Example N! (do-while)
- int number, factorial, n
- cout ltlt "Enter number "
- cin gtgt number
- factorial 1
- n 1
- do
- factorial n
- n
- while(n lt number)
- cout ltlt "The factorial of " ltlt number
- ltlt " is " ltlt factorial ltlt endl
53Which Loop to Use?
- For loop
- Usually best for sums, products, and counting
loops. - While loop
- You want to repeat an action without knowing
exactly how many times it will be repeated. - There are situations when the action should not
be executed. - Do-while loop
- The action should always be executed at least
once. - Otherwise, the do-while loops and while loops are
used in similar situations.
54How to Stop a Loop
- Known number of iterations before the loop stops
(for) - Test for a user-controlled
- condition before or after
- each iteration (while, do-while)
- Use the break command.
55Stop a loop break
- The break command is the same as the one used
previously in switch. - break leaves the current loop immediately. It is
recommended that break be used for situations
where the loop needs to be terminated immediately
(e.g., due to user intervention or if a fatal
error occurs). - Use with care !!
56Example Maximum (while with break)
int value //input value int max0 //maximum
value while(true) cout ltlt "Enter a value (-1
to stop) " cin gtgt value if(value gt
max) max value if(value-1) break
cout ltlt "The maximum value found is " ltlt " is
" ltlt max ltlt endl
57Common Loop Errors
- while(balance ! 0.0)
-
- balance balance - amount
-
- This will lead to an infinite loop!
- for(n1 nltcount n)
-
- cout ltlt "hello" ltlt endl
-
- "hello" only printed once!
- while(balance ! 0.0)
- balance balance - amount
-
- balance may not become equal zero due to
numerical inaccuracies
58Nested Loops
- Nested loops are loops within loops.
// Program to output the // multiplication
table int i //Outer loop counter int
j //Inner loop counter for(i1 ilt10
i) for(j1 jlt10 j) cout ltlt ij ltlt "
" cout ltlt endl
Output 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16
18 20 3 6 9 12 15 18 21 24 27 30
59Programming
- Recursion
- (Ch.6, Section 6-9)
60Recursion
- Recursion is one way to decompose a task into
smaller subtasks. - The smallest example of the same task has a
non-recursive solution. - Example The factorial function
- n! n (n-1) (n-2) ... 1
- or
- n! n (n-1)! and 1! 1
- A recursive solution may be simpler to write
(once you get used to the idea) than a
non-recursive solution. - But a recursive solution may not be as efficient
as a non-recursive solution of the same problem.
61Recursion General Form
- How to write recursively?
- int rec(parameters)
- if(stopping condition)
- return stopping value
- value rec(revised parameters)
- return value
62Example N! Recursion
- int fac(int n)
- int product
- if(n lt 1)
- return 1
- product n fac(n-1)
- return product
-
- void main()
- int number 3
-
- cout ltlt fac(number) ltlt endl
63Execution trace
- fac(3)
- 3 lt 1 ? No.
- product3 3 fac(2)
- fac(2)
- 2 lt 1 ? No.
- product2 2 fac(1)
- fac(1)
- 1 lt 1 ? Yes.
- return 1
- product2 2 1 2
- return product2
- product3 3 2 6
- return product3
- fac(3) has the value 6
64Programming
65Arrays
- An array is a collection of data elements that
are of the same type (e.g., a collection of
integers, collection of characters, collection of
doubles).
66Arrays
- 1-dimensional array.
- 3-dimensional array (3rd dimension is the day).
67Array Declaration 1 Dimension
- Syntax lttypegt ltarrayNamegtltdimensiongt
68Subscripting 1 Dimension
- // array of 10 uninitialized ints
- int A10
- A3 1
- int x A3
69Array Initialization 1 Dimension
70Example Definitions 1 Dimension
- Suppose
- const int N 20
- const int M 40
- const int MaxStringSize 80
- const int MaxListSize 1000
- Then the following are all legal array
definitions. - int A10 // array of 10 ints
- char BMaxStringSize // array of 80 chars
- double CMN // array of 800 doubles
- int ValuesMaxListSize// array of 1000 ints
71Example Smallest Value (1-dimension)
- const int N10
- int AN
- int SmallestValueSoFar, i
- ... // A is input by user
- SmallestValueSoFar A0
- for (i1 iltN i)
- if (Ai lt SmallestValueSoFar)
- SmallestValueSoFar Ai
-
722-D Array Example
int table54
73Programming
- Passing Arrays to Functions
- (Ch.8, p.388-397)
74Passing Array Elements
Individual elements can be passed to a function
like ordinary values.
75Passing Arrays as Parameters
- Arrays can be passed to functions in their
entirety. - All that is required is the address of the first
element and dimensions of the array. - The remainder of the array will be passed by
reference automatically. - Using in the formal parameter specification
indicates that the variable is an array.
76Example Multiple an array by 2
77The const type modifier
- If the function must not change any element of
the array then const should be used in the formal
parameter specification of that array.
78Passing Multidimensional Arrays
- How to pass a multidimensional array to a
function - void displayBoard(int b4)
- // function prototype requires variable name for
arrays - void main()
- int board 44
- ...
- displayBoard(board)
- ...
-
- void displayBoard(int b4)
- // could also be void displayBoard(int
b44) - // but NOT void displayBoard(int b)
- ...
-
- When passing a multidimensional array, only the
size of the 1st dimension is optional, the 2nd,
3rd, etc. dimensions must be specified.
79Programming
- Structures
- (Ch.11, p.567)
80Structures
- A structure is a collection of related data
items, possibly of different types. - In C, structure is a user defined type, called
struct. - A struct is heterogeneous (of different types of
data) whereas an array is homogeneous (of same
type of data) - Examples
- Student record
- student id, name, major, gender, start year,
- Bank account
- account number, name, currency, balance,
- Address book
- name, address, telephone number,
- In database applications, structures are called
records.
81struct basics
- Definition of a structure
- struct ltstruct-typegt
- lttypegt ltidentifier_listgt
- lttypegt ltidentifier_listgt
- ...
-
- Example
- struct Date
- int day
- int month
- int year
-
Each identifierdefines a memberof the
structure.
The Date structure has 3 members, day,
month year.
82struct examples
- Example
- struct BankAccount
- char Name15
- int AcountNo10
- double balance
- Date Birthday
-
- Example
- struct StudentRecord
- char Name15
- int Id
- char Dept5
- char Gender
-
The BankAcount structure has simple, array
and structure types as members.
The StudentRecord structure has 4 members.
83struct basics
- Declaration of a variable of struct type
- ltstruct-typegt ltidentifier_listgt
- Example
- StudentRecord Student1, Student2
- Student1 and Student2 are variables of
StudentRecord type.
Student1
Student2
84Example 1 struct basics
- The members of a struct type variable are
accessed with the dot (.) operator - ltstruct-variablegt.ltmember_namegt
- Example
- strcpy(Student1.Name, "Chan Tai
Man")Student1.Id 12345strcpy(Student1.Dept,
"COMP")Student1.gender 'M'cout ltlt "The
student is "switch (Student1.gender) case
'F' cout ltlt "Ms. " break case 'M' cout ltlt
"Mr. " breakcout ltlt Student1.Name ltlt endl
Student1
85Example 2 struct-to-struct assignment
- The value of one struct type variable can be
assigned to another variable of the same struct
type. - Example
- strcpy(Student1.Name, "Chan Tai
Man")Student1.Id 12345strcpy(Student1.Dept,
"COMP")Student1.gender 'M'Student2
Student1
Student1
Chan Tai Man 12345 M COMP
Chan Tai Man 12345 M COMP
Student2
86Example 3 Nested structures
- We can nest structures inside structures.
- Examples
- struct point double x, ypoint Pstruct
line point p1, p2line Lstruct triangle
point p1, p2, p3triangle T
(P.x, P.y)
(L.p2.x, L.p2.y)
(L.p1.x, L.p1.y)
(T.p2.x, T.p2.y)
(T.p3.x, T.p3.y)
(T.p1.x, T.p1.y)
87Example 4 Nested structures
- We can nest structures inside structures.
- struct line point p1, p2line L
(L.p2.x, L.p2.y)
(L.p1.x, L.p1.y)
88Arrays of structures
- An ordinary array One type of data
- An array of structs Multiple types of data in
each array element.
89Arrays of structures
- ExampleStudentRecord Class100strcpy(Class98
.Name, "Chan Tai Man")Class98.Id
12345strcpy(Class98.Dept, "COMP")Class98.g
ender 'M'Class0 Class98
90Arrays inside structures
- We can use arrays inside structures.
- Examplestruct square point vertex4squar
e Sq - Assign values to Sq using the given square
(4, 3)
(10, 3)
(4, 1)
(10, 1)
x y
x y
x y
x y