Strings and Multi-Dimensional Arrays - PowerPoint PPT Presentation

1 / 60
About This Presentation
Title:

Strings and Multi-Dimensional Arrays

Description:

American Beauty. When using strcat, be careful that you do not overrun the array size. ... tracking news preferences on a web site. 8/22/09. Ethan Cerami, NYU ... – PowerPoint PPT presentation

Number of Views:78
Avg rating:3.0/5.0
Slides: 61
Provided by: Cer8
Learn more at: http://cs.nyu.edu
Category:

less

Transcript and Presenter's Notes

Title: Strings and Multi-Dimensional Arrays


1
Strings andMulti-DimensionalArrays
  • Ethan Cerami
  • New York University

2
Tuesday at a Glance
  • Tuesday
  • Introduction to Strings
  • scanf v. gets
  • Basic String functions strln, strcmp, strcat,
    and strcpy.
  • Basic Encryption
  • Extra PGP (Pretty Good Privacy)

3
Introduction to Strings
4
Introduction to Strings
  • Strings are arrays of characters.
  • Hence, everything you know about arrays can be
    applied to Strings.
  • Example
  • char name"ETHAN"

5
String Storage
  • char name"ETHAN"

E
T
H
A
N
\0
0
1
2
3
4
5
This is the NULL terminator. Indicates the end
of a String. name therefore has 6 elements.
6
Understanding the \0
  • \0 always represents the end of a string.
  • It is added automatically.
  • The following are therefore equivalent
  • char name"ETHAN"
  • char name 'E', 'T', 'H', 'A' ,'N', '\0'
  • If you have a five character name, C will always
    allocate six elements.

7
Inputting Stringsscanf v. gets
8
Inputting Strings
  • To input strings, you can use scanf() or gets().
  • But its important to understand the difference
    between the two.

9
scanf()
s represents the string format specifier.
  • scanf ("s", name)
  • Note that there is no before name. When
    reading in chars, floats, etc., you always need
    the .
  • When reading in Strings, there is no (more on
    this when we learn Pointers.)

10
scanf() continued
  • scanf reads in character data until the first
    white space character.
  • Whitespace space, tab, or new line character.

11
Understanding Whitespace
  • For example, given the following program
  • scanf ("s", name)
  • printf ("Hello, s!", name)
  • If I enter "Ethan Cerami", the program will
    print Hello, Ethan!
  • Thats because scanf reads up until the first
    space character.

12
gets()
  • Gets reads in character data until the new line
    character.
  • For example
  • gets (name)
  • printf ("Hello, s!", name)
  • If I enter "Ethan Cerami", the program will
    print Hello, Ethan Cerami!

13
String.h Basic String Functions
  • strlen, strcmp, strcat, and strcpy

14
strlen
  • C provides a strlen() function.
  • located in ltstring.hgt
  • strlen returns the length of a string (does not
    include the \0 in its calculation.)
  • For example
  • char name100"Gore"
  • printf ("d", strlen (name))

Output 4 Note, however, that the size of the
array is 100
15
Comparing Strings
  • C provides a built-in function to compare two
    strings.
  • strcmp (str1, str2) fucntion
  • If str1 and str2 are identical, the function
    returns 0.

16
Example Password Protection
  • include ltstdio.hgt
  • include ltstring.hgt
  • include ltconio.hgt
  • main ()
  • char password255
  • printf ("Enter password ")
  • scanf ("s", password)
  • while (strcmp (password, "bluemoon") ! 0)
  • printf ("Access Denied. Enter Password ")
  • scanf ("s", password)
  • printf ("Welcome!")
  • getch()

17
Other String Functions
  • String.h includes lots of other string
    manipulation functions
  • strcat() appends one string onto the end of the
    other.
  • strcpy() copies one string to another.

18
Using strcat()
  • include ltstdio.hgt
  • include ltstring.hgt
  • main ()
  • char opening255 "And, the Oscar goes to...
    "
  • char winner255 "American Beauty"
  • strcat (opening, winner)
  • printf ("s", opening)
  • getchar()

Output And, the Oscar goes to... American
Beauty
When using strcat, be careful that you do not
overrun the array size. For example, do not
append a 255 char word to opening.
19
Using strcpy
  • include ltstdio.hgt
  • include ltstring.hgt
  • main ()
  • char word1 "And, the winner is...."
  • char word2255
  • strcpy (word2, word1)
  • printf ("s", word2)
  • getchar()

Output And, the winner is....
This copies the contents of word1 into word2.
20
Encryption
21
Encryption
  • Encryption has been around for centuries.
  • Basic premise is to take a string of characters,
    and scramble the characters up.
  • We will look at three topics today
  • Crypt-o-Text
  • PGP (Pretty Good Privacy)
  • Basic Encryption Program

Note Crypt-o-Text is available for free from
www.savard.com.
22
Extra About PGP
  • Developed by
  • Phil Zimmerman
  • Stands for Pretty Good Privacy
  • Represents the defacto standard for encrypting
    email messages.

23
History of PGP
  • Developed in 1991.
  • Exporting encryption programs is considered the
    equivalent of exporting munitions.
  • PGP was distributed throughout the world via the
    Internet, and Phill Zimmerman was therefore under
    criminal investigation for three years.
  • Charges were eventually dismissed in 1996.
  • http//www.pgp.com/phil/phil-quotes.asp

24
Sending Email
  • Today, electronic mail is gradually replacing
    conventional paper mail, and is soon to be the
    norm for everyone, not the novelty it is today.
    Unlike paper mail, E-mail messages are just too
    easy to intercept and scan for interesting
    keywords. This can be done easily, routinely,
    automatically, and undetectably on a grand
    scale. Phill Zimmerman

Note PGPPhone enables secure voice
communication via the Internet. Its also free.
25
Getting PGP
  • PGP is available for free at http//web.mit.edu/
    network/pgp.html

26
Basic Encryption
  • Our program is real easy to crack, but it does
    illustrate the basics of encryption.
  • The program also provides lots of practice in
    array/string manipulation.
  • Complete code is available in the Course Packet,
    Program 5.3

27
Program Architecture
main
printMenu
encrypt
decrypt
getKey
28
  • main ()
  • int choice
  •  
  • / Print Introduction /
  • printf ("Simple Text Scrambler\n")
  • printf ("\n")
  •  
  • / Prime the while loop with user data /
  • printMenu()
  • scanf ("d", choice)
  • while (choice ! 3)
  • switch (choice)
  • case 1 encrypt()
  • break
  • case 2 decrypt()
  • break
  • default
  • printf ("Invalid Menu Choice.")
  • printf ("Please try again.\n\n")

Print the Introduction
While Loop for Menu Options
29
How to Encrypt a Word
  • Our program uses ASCII Shifting to encrypt
    words.
  • Assume the person enters HELLO, and key 5.
  • Char ASCII Key New ASCII New Char
  • H 72 5 77 M
  • E 69 5 74 J
  • L 76 5 81 Q
  • L 76 5 81 Q
  • 0 79 5 84 T

Encrypted Word
30
  • void encrypt (void)
  • int passkey, index
  • char clear_text255
  • char encrypted_text255
  • passkey getKey()
  • printf ("Enter Word (ALL CAPS) ")
  • scanf ("s", clear_text)
  • / Encrypt word by "shifting up" the ASCII
    Table /
  • for (index0 index lt strlen (clear_text)
    index)
  • encrypted_textindex clear_textindex
    passkey
  • / Make sure to terminate the encrypted_text
    with a NULL character /
  • encrypted_textindex '\0'
  • printLine()
  • printf ("Encrypted String s\n",
    encrypted_text)
  • printLine()

First, we prompt the user for the key, and the
clear_text word.
We then encrypt the word one letter at a time.
We do this by copying each letter and shifting up
the ASCII table.
If we forget the \n terminator, the string may
never end.
31
How to Decrypt a Word
  • To decrypt a word, we shift down the ASCII table.
  • Assume the person enters MJQQT, and key 5.
  • Char ASCII Key New ASCII New Char
  • M 77 -5 72 H
  • J 74 -5 69 E
  • Q 81 -5 76 L
  • Q 81 -5 76 L
  • T 84 -5 79 O

Decrypted Word
32
We prompt for the pass key and the encrypted word.
void decrypt (void) int passkey, index char
clear_text255 char encrypted_text255 pass
key getKey() printf ("Enter Encrypted Word
") scanf ("s", encrypted_text) / Decrypt
word by "shifting down" the ASCII Table / for
(index0 index lt strlen (encrypted_text)
index) clear_textindex encrypted_textinde
x - passkey / Make sure to terminate the
clear_text with a NULL character
/ clear_textindex '\0' printLine() prin
tf ("Decrypted String s\n", clear_text) print
Line()
We then decrypt the word one letter at a time.
We do this by copying each letter and shifting
down the ASCII table.
33
Thursday at a Glance
  • Thursday
  • Introduction to Multi-Dimensional Arrays
  • Declaring, initializing and referencing
    multi-dimensional arrays.
  • Putting it all together Basic Example
  • Hunt the Wumpus Advanced Example

34
Introduction to Multi-Dimensional Arrays
35
Why Use Multi-Dimensional Arrays?
  • So far we have only looked at one dimensional
    arrays.
  • Example float stock5
  • But, what if we want to track stocks for more
    than one company?
  • Answer use multi-dimensional arrays.

36
Arrays and SpreadSheets
  • Arrays are used to represent tables of data.
  • They are therefore very similar to spreadsheets.

Columns
Rows
37
Examples
  • There are lots of potential applications for
    multi-dimensional arrays
  • tracking stock portfolios.
  • tracking the temperature in multiple cites.
  • tracking all students grades or registered
    courses.
  • tracking news preferences on a web site.

38
How many Dimensions?
  • In C, you can create arrays with more than two
    dimensions.
  • For example, you can create a six dimensional
    arrays.
  • For this course, however, we will stick to one
    and two dimensional arrays.

39
Declaring / Initializing Multidimensional Arrays
40
Declaration
  • Template
  • data_type var_name number of rowsnumber of
    columns
  • Examples
  • float stocks35
  • Track three different companies over five days.
  • int temp 105
  • Track ten different city temperatures over five
    days.

41
Initialization
  • To initialize a multi-dimensional arrays, use
    embedded brackets.
  • Examples
  • int a22 1,2, 3,4
  • will create this array

1
2
3
4
42
Initialization (cont.)
  • If there are not enough initializers for a row,
    the remaining elements are set to 0.
  • Example
  • int a22 1, 3,4
  • will create this array

1
0
3
4
43
Referencing Multi-Dimensional Arrays
44
Referencing Elements
  • To reference a single dimensional array, you
    provide a single index value.
  • printf ("f", stock3)
  • To reference a multi-dimensional array, you
    provide two index values
  • printf ("f", stock12)
  • Again, it is useful to think of spreadsheets.

45
Passing Multi-Dimensional Arrays to Functions
46
Passing Arrays
  • To pass a multidimensional array
  • indicate the array with double brackets.
  • must indicate the number of columns (number of
    rows is optional, ignored)
  • Example
  • void makeHot (int temp5)

47
Putting it all together
48
Putting it all together
  • Lets look at an example of creating,
    initializing, and passing a multi-dimensional
    array.
  • This program tracks temperatures in three cities
    over five days.
  • The function modifies the array by adding 10
    degrees to each temperature value.

49
include ltstdio.hgt define NUMCITIES 3 define
NUMDAYS 5 void makeHot (int NUMDAYS) main
() int i,j int tempNUMCITIESNUMDAYS
67, 68, 69, 70, 71, 44, 45, 46, 47,
48, 31, 32, 33, 34, 35 makeHot
(temp) for (i0 iltNUMCITIES i) for
(j0 jlt NUMDAYS j) printf ("\td",
tempij) printf ("\n")
Function Prototype We must indicate the number
of columns. Double brackets tell the compiler
that this is a two dimensional array.
Array declaration and initialization.
Whenever printing out the contents of a
multi-dimensional array, you must use a nested
for loop.
50
void makeHot (int thermoNUMDAYS) int
i,j for (i0 ilt NUMCITIES i) for (j0
jlt NUMDAYS j) thermoij 10
To iterate through all elements in a
multi-dimensional array, we use a nested for loop.
Output 77 78 79 80 81 54 55 56 57 58 41 42 43 44
45
51
Call by Reference
  • Single and multi-dimensional arrays are always
    passed by reference.
  • Hence if you pass an array to a function, and
    modify the array, you will modify the original
    array.

52
Hunt the Wumpus
53
Why Hunt the Wumpus?
  • Hunt the Wumpus is a text-based game that makes
    extensive use of multi-dimensional arrays.
  • The full program is available in the course
    packet, Program 5.6

54
Game Rules
  • The goal of the game is quite simple slay the
    Wumpus before he gobbles you up. Here is how it
    works
  • You start out in a room. From this room, you can
    move in any of the compass directions North,
    South, East or West.
  • To move, simply indicate the direction in
    lowercase. For example, to move north, just type
    n.

55
Game Rules (cont.)
  • When you enter a new room, one of two things may
    happen
  • You might smell a Wumpus This means that the
    Wumpus is hiding in one of the adjoining rooms.
    If you walk into one of these rooms, you get
    gobbled up.
  • You might feel a cool breeze This means that
    there is a bottomless pit in one of the adjoining
    rooms. If you walk into a room with a bottomless
    pit, you fall to a miserable death.
  • In addition to moving, you can also shoot an
    arrow in one of four directions.
  • To shoot an arrow, simply indicate the direction
    in upper case. For example, to shoot east, just
    type E. But, remember that you only have three
    arrows!

56
Game Map
  • The Game takes place on a 2D Map
  • define MAPHEIGHT 7
  • define MAPWIDITH 7
  • char mapMAPHEIGHTMAPWIDTH
  • Within this map, we may have any of the following
    characters
  • Wall
  • W Wumpus
  • _at_ Player
  • P Bottomless pit

57
Example Game Map







W
_at_
P


P




P









58
Debug Mode
  • The game contains a debug mode.
  • Just set
  • int debug1
  • This will draw the 2D map after each move.
  • Very helpful for figuring out how the rest of the
    program works.

59
printMap() Function for Debugging
  • void printMap (char mapMAPWIDTHMAPHEIGHT)
  • int i,j
  • for (j0 j lt MAPHEIGHT j)
  • for (i0 ilt MAPWIDTH i)
  • printf ("c", mapij)
  • printf ("\n")

Nested for loop to print out each square in the
2D map.
60
Program Structure
Main Function
initMap Initializes a different random map for
each games
smell() Tells player of nearby danger.
move() Moves the player to new map location.
shoot() Shoots arrow in specified direction.
Write a Comment
User Comments (0)
About PowerShow.com