1 / 60

Strings and Multi-Dimensional Arrays

Learn fundamentals of strings and arrays in C with functions like strlen, strcmp, strcat, and understanding encryption concepts.

dbash
Download Presentation

Strings and Multi-Dimensional Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Strings andMulti-DimensionalArrays Ethan Cerami New York University Ethan Cerami, NYU

  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) Ethan Cerami, NYU

  3. Introduction to Strings Ethan Cerami, NYU

  4. Introduction to Strings • Strings are arrays of characters. • Hence, everything you know about arrays can be applied to Strings. Example: char name[]="ETHAN" Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  7. Inputting Strings:scanf v. gets Ethan Cerami, NYU

  8. Inputting Strings • To input strings, you can use scanf() or gets(). • But it’s important to understand the difference between the two. Ethan Cerami, NYU

  9. %s represents the string format specifier. scanf() 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.) Ethan Cerami, NYU

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

  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! • That’s because scanf reads up until the first space character. Ethan Cerami, NYU

  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! Ethan Cerami, NYU

  13. String.h Basic String Functions strlen, strcmp, strcat, and strcpy Ethan Cerami, NYU

  14. strlen • C provides a strlen() function. • located in <string.h> • strlen returns the length of a string (does not include the \0 in its calculation.) • For example: char name[100]="Gore"; printf ("%d", strlen (name)); Output: 4 Note, however, that the size of the array is 100 Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  16. Example: Password Protection #include <stdio.h> #include <string.h> #include <conio.h> main () { char password[255]; printf ("Enter password: "); scanf ("%s", password); while (strcmp (password, "bluemoon") != 0) { printf ("Access Denied. Enter Password: "); scanf ("%s", password); } printf ("Welcome!"); getch(); } Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  18. Using strcat() #include <stdio.h> #include <string.h> main () { char opening[255] = "And, the Oscar goes to... "; char winner[255] = "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. Ethan Cerami, NYU

  19. Using strcpy #include <stdio.h> #include <string.h> main () { char word1[] = "And, the winner is...."; char word2[255]; strcpy (word2, word1); printf ("%s", word2); getchar(); } Output: And, the winner is.... This copies the contents of word1 into word2. Ethan Cerami, NYU

  20. Encryption Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  22. Extra: About PGP • Developed by Phil Zimmerman • Stands for Pretty Good Privacy • Represents the defacto standard for encrypting email messages. Ethan Cerami, NYU

  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 Ethan Cerami, NYU

  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. It’s also free. Ethan Cerami, NYU

  25. Getting PGP • PGP is available for free at: http://web.mit.edu/network/pgp.html Ethan Cerami, NYU

  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 Ethan Cerami, NYU

  27. Program Architecture main encrypt printMenu decrypt getKey Ethan Cerami, NYU

  28. Print the Introduction 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"); break; } printMenu(); scanf ("%d", &choice); } return 0; } 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 Ethan Cerami, NYU

  30. 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. void encrypt (void) { int passkey, index; char clear_text[255]; char encrypted_text[255]; passkey = getKey(); printf ("Enter Word (ALL CAPS): "); scanf ("%s", clear_text); /* Encrypt word by "shifting up" the ASCII Table */ for (index=0; index < strlen (clear_text); index++) encrypted_text[index] = clear_text[index] + passkey; /* Make sure to terminate the encrypted_text with a NULL character */ encrypted_text[index] = '\0'; printLine(); printf ("Encrypted String: %s\n", encrypted_text); printLine(); } 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 Ethan Cerami, NYU

  32. We prompt for the pass key and the encrypted word. void decrypt (void) { int passkey, index; char clear_text[255]; char encrypted_text[255]; passkey = getKey(); printf ("Enter Encrypted Word: "); scanf ("%s", encrypted_text); /* Decrypt word by "shifting down" the ASCII Table */ for (index=0; index < strlen (encrypted_text); index++) clear_text[index] = encrypted_text[index] - passkey; /* Make sure to terminate the clear_text with a NULL character */ clear_text[index] = '\0'; printLine(); printf ("Decrypted String: %s\n", clear_text); printLine(); } 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 Ethan Cerami, NYU

  34. Introduction to Multi-Dimensional Arrays Ethan Cerami, NYU

  35. Why Use Multi-Dimensional Arrays? • So far we have only looked at one dimensional arrays. • Example: float stock[5]; • But, what if we want to track stocks for more than one company? • Answer: use multi-dimensional arrays. Ethan Cerami, NYU

  36. Arrays and SpreadSheets • Arrays are used to represent tables of data. • They are therefore very similar to spreadsheets. Columns Rows Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  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. Ethan Cerami, NYU

  39. Declaring / Initializing Multidimensional Arrays Ethan Cerami, NYU

  40. Declaration • Template: • data_type var_name [number of rows][number of columns] • Examples: • float stocks[3][5]; • Track three different companies over five days. • int temp [10][5]; • Track ten different city temperatures over five days. Ethan Cerami, NYU

  41. Initialization • To initialize a multi-dimensional arrays, use embedded brackets. • Examples: int a[2][2] = {{1,2}, {3,4}}; will create this array 1 2 3 4 Ethan Cerami, NYU

  42. Initialization (cont.) • If there are not enough initializers for a row, the remaining elements are set to 0. • Example: int a[2][2] = {{1}, {3,4}; will create this array 1 0 3 4 Ethan Cerami, NYU

  43. Referencing Multi-Dimensional Arrays Ethan Cerami, NYU

  44. Referencing Elements • To reference a single dimensional array, you provide a single index value. • printf ("%f", stock[3]); • To reference a multi-dimensional array, you provide two index values: • printf ("%f", stock[1][2]); • Again, it is useful to think of spreadsheets. Ethan Cerami, NYU

  45. Passing Multi-Dimensional Arrays to Functions Ethan Cerami, NYU

  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 temp[][5]); Ethan Cerami, NYU

  47. Putting it all together Ethan Cerami, NYU

  48. Putting it all together • Let’s 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. Ethan Cerami, NYU

  49. #include <stdio.h> #define NUMCITIES 3 #define NUMDAYS 5 void makeHot (int [][NUMDAYS]); main () { int i,j; int temp[NUMCITIES][NUMDAYS] = { {67, 68, 69, 70, 71}, {44, 45, 46, 47, 48}, {31, 32, 33, 34, 35}}; makeHot (temp); for (i=0 ; i<NUMCITIES; i++) { for (j=0; j< NUMDAYS; j++) printf ("\t%d", temp[i][j]); 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 thermo[][NUMDAYS]) { int i,j; for (i=0; i< NUMCITIES; i++) for (j=0; j< NUMDAYS; j++) thermo[i][j] += 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

More Related