Title: Presentation Number 5
1Presentation Number 5
2The Switch Statement
3The Switch Statement
- You can write
- if (letter 'a')
- printf("The letter is a\n")
- else
- if (letter 'b')
- printf("The letter is b\n")
- else
- if (letter 'c' letter 'C')
- printf("The letter is either c or C\n")
- else
- printf("This is not a familiar
letter\n")
4The Switch Statement
A switch statement is a multi-way conditional
statement.
- switch ( letter )
-
- case 'a'
- printf("The letter is a\n")
- break
- case 'b'
- printf("The letter is b\n")
- break
- case 'c'
- case 'C'
- printf("The letter is either c or C\n")
- break
- default
- printf("This is not a familiar letter\n")
There is an expression to be evaluated. It must
have an integer value.
The cases are labels to jump to according to the
value of the expression. There is a defalut label.
5The Switch Statement
- switch ( letter )
-
- case 'a'
- printf("The letter is a\n")
- break
- case 'b'
- printf("The letter is b\n")
- break
- case 'c'
- case 'C'
- printf("The letter is either c or C\n")
- break
- default
- printf("This is not a familiar letter\n")
When a switch jumps to a chosen case, it executes
the statements from that point on.
Unless stopped it will fall through to the next
case.
break causes the program to jump to the first
statement after the switch.
6Simple Calculator
- int main()
-
- double x 0.0, y 0.0
- char oper 0
- printf("Enter a simple math operation\n")
- scanf("lf c lf", x, oper, y)
- switch( oper )
-
- case ''
- printf("Value lf\n", x y )
- break
- case '-'
- printf("Value lf\n", x - y )
- break
- case ''
- printf("Value lf\n", x y )
- break
- case '/'
- printf("Value lf\n", x / y )
Sometimes you might decide not to use a default
label (although it does not hurt to have one even
if it is empty).
SimpleCalc.c
7Thinking About Algorithms
8Advanced Subsequences
- You are given a set of numbers.
- How do you calculate the length of the longest
increasing sub-sequence when the sequence does
not have to be of successive numbers? - Example input
- Sequence length 8
9Advanced Subsequences
- Here are a few questions that you should answer
first - Do you have to store the input numbers?
- What is the brute force solution? How bad is
it? - Is it feasible to solve the problem in one pass
over the number? - How did YOU find the length in this input set?
10Advanced Subsequences
- Input
- Generally, it does not matter how many numbers
are in the input set. Lets assume that we have n
numbers. - Lets assume that part of the problem is solved.
We will figure out later what this means. - Lets assume that we are now working on the ith
element and we want to add it to a subsequence. - We can add it at the beginning or at the end of a
subsequence
11Solution 1 Adding The First Element
- Elements
- If we are adding the ith element as first element
in a subsequence, what kind of information about
the next elements can we use to make the
calculation easier?
12Solution 1 Adding The First Element
- Elements
- Lengths
- For each element j (where j gt i) the Lengths
array stores the length of the longest
subsequence whose first number is the jth number. - If (element j gt element i) then
- length i 1 length j
- If (Lengthsi lt length i) then
- Lengthsi length i
- The maximal length is the biggest number in the
Lengths array.
13Solution 2 Adding The Last Element
- Elements
- Lengths
- For each element j (where j lt i) the Lengths
array stores the length of the longest
subsequence whose last number is the jth number. - If (element j lt element i) then
- length i 1 length j
- If (Lengthsi lt length i) then
- Lengthsi length i
- The maximal length is the biggest number in the
Lengths array.
14Multi-Dimensional Arrays
- Arrays allow us to store a block of many
variables of the same type and access them with a
single name. - Arrays can have more than one dimension.
- int numbers1002
- double values10319
- float mat33
The first element is mat00 and the last is
mat22
mat
15Functions
16Function Definition
- type name(type name1, type name2, )
-
- function body
- return value
-
- A function is a group of declarations and
statements. - It has a name.
- It has a type.
- It has a value.
- It can have parameter variables.
- main is a function.
17Function Definition
- double abs_value( double x )
-
- if ( x gt 0.0 )
- return x
- else
- return -x
18The Return Statement
- double abs_value( double x )
-
- if ( x gt 0.0 )
- return x
- else
- return -x
return ends the execution of the function and
returns a value to the calling function.
The type of the value returned must be the same
as the return-type defined for the function.
19Example
- include ltstdio.hgt
- double abs_value( double x )
-
- if ( x gt 0.0 )
- return x
- else
- return -x
-
- int main()
-
- double num 0.0, absNum 0.0
- printf("enter a number\n")
- scanf("lf",num)
- absNum abs_value(num)
Here we define two functions abs_value and
main. A function must be defined or at least
declared before it can be used.
AbsValue.c
20Example
- include ltstdio.hgt
- double abs_value( double x )
-
- if ( x gt 0.0 )
- return x
- else
- return -x
-
- int main()
-
- double num 0.0, absNum 0.0
- printf("enter a number\n")
- scanf("lf",num)
- absNum abs_value(num)
These are the function calls. The variable absNum
is assigned the value that was returned by the
function abs_value with parameter num.
AbsValue.c
21Why use functions?
- They break a problem down into smaller sub-tasks.
- makes it easier to solve complex problems.
- They generalize a repeated set of instructions.
- We dont have to keep writing the same thing over
and over again. - printf and scanf are good examples
- They make a program much easier to read, maintain
and debug.
22What Does This Program Do?
- int main()
-
- int numArrayMAX_NUMBERS
- int numValues 0
- numValues readNumbers( numArray, MAX_NUMBERS
) - if ( numValues ! 0 )
-
- sortNumbers( numArray, numValues )
- printUniqueNumbers( numArray, numValues)
-
- else
-
- printf("No numbers were read!\n")
- return -1
-
- return 0
23The Great Void
- Sometimes there is no reason for a function to
return a value - In these cases, the function return type should
be void. - If the return keyword is used within such a
function it exits the function immediately. A
value should not be specified. - Calling return in a function returning void is
not obligatory. - If the function receives no parameters, the
parameter list should be replaced by void (or
be left empty).
24Example
The function does not recieve parameters and does
not return a value.
- void ShowHelp()
-
- printf("This function explains what the program
does\n") - printf("It prints this explanation!!")
-
- int main()
-
- char choice 0
- printf("Please enter your selection ")
- scanf("c", choice)
- if (choice 'h')
- ShowHelp()
- .
- .
- .
25Function Declaration
26Function Declaration
- All of the software projects in C are composed of
multiple functions. - Most software projects in C are composed of more
than one file - We want to define a function once, and use it
many times. - To do so, the function must be declared in every
file in which its called, before its called for
the first time
27Function Declaration
- include ltstdio.hgt
- / Function Declaration! /
- int factorial(int a)
- int main()
-
- int num, factValue
- printf("enter a number\n")
- scanf("d", num)
- factValue factorial(num)
- printf(The factorial of d is d\n", num,
factValue) - return 0
A function is declared as follows type name(type
name1, type name2, )
Factorial.c
28Function Declaration
- int factorial(int a)
-
- int i, b 1
- for (i 1 i lt a i)
- b i
- return b
A function declaration allows you to use the
function ... however, you must also define the
function
Factorial.c
29Function Declaration
- stdio.h actually contains a large set of function
declarations - The include directive tells the compiler to
insert these declarations into the file, so that
these functions could be called
30Developing large programs
pgm.h
includes defines list of prototypes
main.c
fct.c
prn.c
includes pgm.h
includes pgm.h
includes pgm.h
31Variables and Functions
32Call By-Value
- Function arguments are passed to the function by
copying their values rather than giving the
function direct access to the actual variables. - A change to the value of an argument in a
function body will not change the value of
variables in the calling function.
33Call By-Value
- include ltstdio.hgt
- int compute_sum(int num)
- int main()
-
- int num3, sum0
- printf("d\n", num)
- sum compute_sum(num)
- printf("d\n", num)
- printf("d\n", sum)
- return 0
Function declaration
3 is printed
what happens to n and sum here?
ByValue.c
34Call By-Value
- int compute_sum( int num )
-
- int sum 0
- for ( num gt 0 --num )
- sum num
- return sum
sum the integers from 1 to n
This num is local. Its value is the same as the
value of the variable that was sent to the
function.
sum is local to the function.
local num and sum are changed
ByValue.c
35Riddle me this
int main() int n 0, fact 0
printf("enter a number\n") scanf("d",n)
fact factorial(n) printf("d!d\n", n,
fact) / What will this print? /
printf("n d\n", n) return 0
- include ltstdio.hgt
- int factorial(int n)
-
- int fact 1
- while (ngt1)
-
- fact n
- n--
-
- return fact
36Scope Rules
- Scope rules apply also to functions.
- A variable declared within a function is
unrelated to variables declared elsewhere, even
if they have the same name - A function cannot access variables that are
declared in other functions
37Magic Square Example
38Example Magic-Square
39 Magic Square
- include ltstdio.hgt
- int IsMagic (int mat33)
- / Input A 3x3 matrix as nine integers ordered
by columns / - / Output is it a magic square /
- int main (void)
-
- int mat33
- int row, col, ret
- for (row0 rowlt3 row)
-
- for (col0 collt3 col)
-
- ret scanf ("d", matrowcol)
- if ( ret 0 ret EOF )
-
- printf ("Error, input needs to be nine
integers.\n") - return -1
-
Loop across all the rows
Loop across the elements of the row
Read a number
Check the scanf worked correctly
MagicSquare.c
40Magic Square
Let the function check for magic squareness
- if (IsMagic (mat) 1)
- printf ("the input is a magic square.\n")
- else
- printf ("the input square is NOT a magic
square.\n") - return 0
MagicSquare.c
41Magic Square
- / Function check if a square is a magic square
/ - / input a 3x3 matrix of integers /
- / output 1 - if it is a magic square 0
otherwise / - int IsMagic (int mat33)
-
- int i, j
- int sum_r, sum_c, ref_sum, r_diag, l_diag
- / init ref_sum with first row sum /
- ref_sum 0
- for (j0 jlt3 j)
- ref_sum mat0j
The function recieves the matrix as a parameter.
This is known as passing parameters by-reference.
MagicSquare.c
42Magic Square
- / check rows and cols together /
- for (i0 ilt3 i)
-
- sum_r sum_c 0
- for (j0 jlt3 j)
-
- sum_r matij
- sum_c matji
-
-
- if (sum_r ! ref_sum sum_c ! ref_sum)
- return 0
-
Instead of repeating the code once for rows and
once for columns we use the same loops for both.
MagicSquare.c
43Magic Square
- / check main diagonals /
- r_diag l_diag 0
- for (i0 ilt3 i)
-
- r_diag matii
- l_diag mati2-i
-
-
- if (r_diag ! ref_sum l_diag ! ref_sum)
- return 0
- return 1
MagicSquare.c