Title: Presentation Number 8
1Presentation Number 8
2Recursions
3A recursive definition
- C functions can call themselves!
- When a function calls itself we call this a
recursive call. - Two things you must remember about recursions
- Change the parameters from call to call!!!
- Make sure you defined a boundary condition!!!
4Towers of Hanoi
- Goal
- Move the entire tower to the right peg.
- Constraints
- Only move one disk at a time.
- Never place a larger disk on a smaller one.
5Towers of Hanoi
Step 1 Move n 1 disks to the middle peg.
6Towers of Hanoi
Step 2 Move a single disk from the left peg to
the right peg.
7Towers of Hanoi
Step 3 Move n 1 disks from the middle peg to
the right peg.
8Towers of Hanoi
- void hanoi(int size, int src, int dest, int aux)
-
- if ( size 1 )
-
- printf( "Shift disc from peg d to peg
d.\n", src, dest ) - return
-
- hanoi( size 1, src, aux, dest )
- hanoi( 1, src, dest, aux )
- hanoi( size 1, aux, dest, src )
-
- int main()
-
- hanoi( 3, 1, 3, 2 )
- return 0
-
9Pointers
10Declaring a pointer variable
- A pointer is declared by adding a before the
variable name. - A pointer is a variable that contains an address
in memory. - The address should be the address of a variable
or an array that we defined.
type variable_name
11Referencing
- The unary operator gives the address of a
variable - The statement
- ptr a
- assigns the address of a to the pointer
variable ptr. - The variable pointer ptr now points to variable
a.
12Dereferencing
- The unary operator is the dereferencing
operator. - It is applied on pointers.
- It accesses the object the pointer points to.
- Follow the pointer and perform the operation on
the actual memory that the pointer points to.
13Swap Example
- void swap(int x, int y)
-
- int temp x
- x y
- y temp
-
- int main()
-
- int x 5, y 7
- swap( x, y )
- printf( x d and y d\n, x, y )
- return 0
We define the swap function so it gets pointers
to integers instead of integers.
x 7 and y 5
14Arrays and Pointers
- An array arr holds the address of its first
element arr0. - arr is actually a pointer to arr0.
- char arr10char ptr NULLptrarr
- Both ptr and arr now point to arr0.
15Pointer arithmetic
- Pointers can be incremented and decremented
- If p is a pointer to a particular type, p1
yields the correct address of the next variable
of the same type. - p, pi, and p i also make sense.
- If p and q are of the same type and point to
elements in an array, q-p is the number of
elements between p and q.
16Strings
17Strings
- An array of characters.
- Used to store text.
- Can be initialized as follows
- char str20 "Hello World"
The string terminating character
18The Terminator
- Strings terminate with a '\0' character (ascii
code 0). - This is a convention used to know where the
string ends. - It means that in order to hold a string of N
characters we need an array of length N 1. - So the previous initialization is equivalent to
- char str20 'H', 'e', 'l', 'l', 'o', ' ',
'w', 'o', 'r', 'l', 'd', '\0'
19The fool on the null
I
'
m
a
f
u
l
l
s
t
r
i
n
g
'\0'
- int main()
-
- char str20 "I'm a full string"
- printf("s\n", str)
- str7 'o' str8 'o'
- printf("s\n", str)
- str10 '\0'
- printf("s\n", str)
- str10 s
- printf("s\n", str)
- return 0
str
20Strings
- It is useful to think of strings as having
- variable length (determined by the \0)
- maximum length (determined by the array)
- Up to programmer to make sure the length is not
overrun.
21Strings
- String constant
- Written between double quotes (e.g. hello)
- Considered as pointers (e.g. char p hello)
- char pstr "abcde"
- vs.
- char astr6 "abcde"
pstr
a
b
c
d
e
'\0'
astr
a
b
c
d
e
'\0'
22Reading strings
- There are several ways of accepting strings as
input from the user - Read one character at a time ... getchar()
- Read a string until a white space ... scanf()
- Read a string until a newline or an EOF ... gets()
23Reading Strings getchar
- define MAX_LENGTH 20
- int main()
-
- char c 0, strMAX_LENGTH 1 0
- int i 0
- printf("Please enter a string\n")
-
- c getchar()
- while (c gt 0 c ! '\n' i lt
MAX_LENGTH) -
- stri c
- c getchar()
- i
-
- stri '\0'
Reserve an additional place for the '\0'
character.
getchar returns a negative number on failiure
Don't forget to add the '\0' character
24Reading Strings - scanf
- define MAX_LENGTH 10
- int main()
-
- char strMAX_LENGTH 1 0
-
- printf("Please enter a string\n")
- scanf(" 10s", str)
- printf("The string you entered is - s\n", str)
- return 0
Reserve an additional place for the '\0'
character.
Read the string
25Reading Strings - scanf
- scanf reads letters until a space or newline
('\n') is encountered. - The maximum length can be stated in the
parentheses - scanf(10s, str)
- This will read in 10 letters, plus the '\0' sign
(so str should have place for 11 characters). - scanf does not read the white space ... so if you
read a character after the scanf ... it will read
the white space!
26Reading Strings - gets
- define MAX_LENGTH 10
- int main()
-
- char strMAX_LENGTH 1 0
-
- printf("Please enter a string\n")
- gets(str)
- printf("The string you entered is - s\n", str)
- return 0
Reserve an additional place for the '\0'
character.
Read the string
27Reading Strings - gets
- gets reads letters until a newline or an EOF is
encountered. - There is no way to limit the length of the
string. - If the string is too long ... it is a problem.
- gets returns NULL in case of an error or an EOF.
28Examples
29Replace Characters
- void replace(char str, char replace_what, char
replace_with) -
- int i0
- for (i 0 stri ! '\0' i)
-
- if (stri replace_what)
- stri replace_with
-
Loop until a '\0' character
30The Number of Words in a String
- include ltctype.hgt
- int word_cnt(char str)
-
- int cnt 0
- while (str ! '\0')
-
- while (isspace(str))
- str
- if (str ! '\0')
-
- cnt
- while (!isspace(str) str ! '\0')
- str
-
-
- return cnt
Loop until the end of the string
Skip spaces (isspace tells you if a chracter is a
white space)
Did not reach the end of the string
Skip the word
31String library
- Like in the case of stdio.h and math.h, we have a
special library for handling strings. - We should include ltstring.hgt
- There are other libraries, such as ctype.h that
have functions that we can use. - isspace ... Tells us if a character is a white
space.
32String library
- Functions
- strlen(const char s) returns the length of s
- strcmp(const char s1,const char s2) compares
s1 with s2 - strcpy(char s1, const char s2)copies to
contents of s2 to s1 - and more
33The Length of a String
- int strlen( const char str )
-
- int n 0
-
- for ( n 0 str ! '\0' str )
- n
- return n
34My Strcmp
- int myStrcmp( const char src, const char trg )
-
- int i0
- while ( srci ! \0 srci trgi )
- i
- return srci trgi
35Memory Allocation
36Memory Allocation
- Array variables have fixed size, used to store a
fixed and known amount of variables known at
the time of compilation. - This size cant be changed after compilation
- However, we dont always know in advance how much
space we would need for an array or a variable - We would like to be able to dynamically allocate
memory.
37Malloc Memory Allocation Function
- The function malloc
- is used to dynamically allocate nBytes in memory
- returns a pointer to the allocated memory.
- In case of failure returns NULL.
- You should
- Always check if memory was successfully
allocated. - Remember to include ltstdlib.hgt
void malloc(unsigned int nBytes)
38How Can We Use The Memory?
- The type (void ) specifies a general pointer,
which can be cast to any pointer type. - Casting tells the pointer that it points to the
appropriate type of memory.
ptr (int)malloc(nsizeof(int))
39What is this sizeof ?
- The sizeof operator gets a variable or a type as
an input and outputs its size in bytes -
- double x
- s1sizeof(x) / s1 is 8 /
- s2sizeof(int) / s2 is 4 /
40Free the allocated memory segment
- We use the free function to free allocated memory
pointed to by a pointer. - If the pointer doesnt point to an area allocated
by malloc, a run-time error occurs. - Always free the allocated memory once you dont
need it anymore. Otherwise, you may run out of
memory before you know it!
void free(void ptr)
41Memory Allocation Example
- include ltstdlib.hgt
- include ltstdio.hgt
- int main()
-
- int i0, n0, ptr NULL
- printf("How many numbers do you want to
enter?\n") - scanf("d",n)
- ptr (int)malloc(nsizeof(int))
- if (ptr NULL)
-
- printf("Memory allocation failed!\n")
- return -1
-
Allocate an array of n integers
Check that memory allocation was successful
42Memory Allocation Example
- printf("Please enter numbers now\n")
- for(i0 iltn i)
- scanf("d", ptri)
- printf("The numbers in reverse order are - \n")
- for(in-1 igt0 i--)
- printf("d ",ptri)
- if( ptr ! NULL )
- free(ptr)
- return 0
-
Free the allocated memory