IPC144 Introduction to Programming Using C Week 1 – Lesson 2 (Pages 5 to 9 in IPC144 Textbook)
1 IPC144 Session 15 The C Programming Language. 2 Objectives To define arrays within the C language...
-
Upload
gavin-cole -
Category
Documents
-
view
226 -
download
2
Transcript of 1 IPC144 Session 15 The C Programming Language. 2 Objectives To define arrays within the C language...
1
IPC144Session 15
The C Programming Language
2
Objectives
To define arrays within the C languageTo use arrays in a C programTo pass arrays between functionsDefine what a string isList the three methods strings can be stored in a computer.Use arrays to store stringsList the standard C functions for manipulating stringsList the parameters for the C string functions, and their restrictionsUse the C string functions to manipulate strings
3
The C Language
ArraysRecall from or earlier discussions of Arrays, that we will be dealing with one-dimensional arrays (like a column of an Excel spreadsheet).
A one-dimensional array is also called a list or a vector.
Each element is numbered uniquely
For C we will use the same notation we used in flowcharts:
tableName[index]
the tableName is a variable, and therefore you apply the variable naming standards when declaring a table.the index is the element numberIn C, the index always start at zero
4
The C Language
Arrays, continuedOne dimensional tables
If a table called myTab contained:
element# element0 Red1 Orange2 Yellow3 Green4 Blue5 Violet
myTab[0] contains RedmyTab[4] contains ??
5
The C Language
Arrays, continuedWhat is the data type of a table?
The data type can be any of the types we discussed- the compiler uses this information so that it knows how to interpret the data once it gets there
How are arrays stored inside the computer?
Arrays are stored in contiguous memory locations, where the first location is pointed to by a variable that knows how to get to the start of the list of elements
How are arrays declared?
6
The C Language
Arrays, continuedAnatomy of an array declaration:
int myTab[5];
The maximum number of elements in the array (numbered 0 to n - 1)
The name of the table- following the variable naming standards
Data type of the array
This is an implicit declaration of a pointer (myTab) that points to a fixed block of memory that will contain the elements of the array.
This means that when you use the array name by itself, you are using a pointer variable!
7
The C Language
Arrays, continuedWrite a program that reads 10 floats from the user and stores them into an array.
8
The C Language
Arrays, continued#include <stdio.h>#define ARRAY_SIZE 10
int main(void){ int counter, ch; float theArray[ARRAY_SIZE];
for (counter = 0; counter < 10; counter = counter + 1) { scanf("%f", &theArray[counter]); while((ch = getc(stdin)) != EOF && ch != '\n'); }
for (counter = 0; counter < ARRAY_SIZE; counter = counter + 1) printf("theArray[%d] = %1.2f\n", counter, theArray[counter]);} Something new:while((ch = getc(stdin)) != EOF && ch != '\n');
This causes the computer to discard anything that happens to have been left in the keyboard buffer after the last read - essentially this cleans up in preparation of another keyboard read.
9
The C Language
Arrays, continuedWhat is the most efficient method to pass an array to a function, in order that the function may change the contents of one of the elements (or many elements) of the array?
Pass-by-reference.
There are two possible syntax rules for declaring a pointer to an array in a function prototype or a function declaration (shown below):
myFunc(int mytab[]){}
or myFunc(int *myTab){}
The following is a program written to use a function to print a table:
10
The C Language
Arrays, continued#include <stdio.h>#define TAB_SIZE 10
void printFunction(int tbl[]);
int main(void){ int i; int table[TAB_SIZE];
for (i = 0; i < 10; i = i + 1) { table[i] = i * 2; }
printFunction(table);}
void printFunction(int tbl[]){ int i;
for (i = 0; i < TAB_SIZE; i= i + 1) printf("table[%d] = %d\n", i, tbl[i]);}
11
The C Language
Arrays, continuedWrite a program that reads 5 numbers from the user and stores them into a 5 element array. Create a function that flips the array upside down. The first element becomes the last, the last becomes the first. The second element becomes the second last, the second last element becomes the second and so on.
12
Strings
13
The C Language
StringsStrings
What is a string?
Strings are a collection of characters treated as a unit
A word, sentence, paragraph or book can all be considered strings
Even a single character can be considered a string- we shall see why shortly
There is also an allowance for an empty string- that is a string containing no characters
14
The C Language
Strings, continuedHow are strings defined to the computer?
Strings
Variablelength
Fixedlength
Lengthcontrolle
dDelimited
15
The C Language
Strings, continued
Fixed Length
Strings
Variablelength
Fixedlength
Lengthcontrolle
dDelimited
A R I S T O T L E
Non character data
16
The C Language
Strings, continued
Length Controlled
Strings
Variablelength
Fixedlength
Lengthcontrolle
dDelimited
A R I S T O T L E9
Length
17
The C Language
Strings, continued
Delimited
Strings
Variablelength
Fixedlength
Lengthcontrolle
dDelimited
A R I S T O T L E \0
Delimiter
18
The C Language
Strings, continued
We have used the '\n' in our programs. C identifies this as the new-line character.
The ‘\0’ is another ‘special’ character in C- it represents the ‘null’ character
It is one of those strange things about computers - they need to have something that represents nothing- null
The null character, as far as the computer is considered, is a legitimate, normal character
A R I S T O T L E \0
Delimiter
19
The C Language
Strings, continuedIf we remember the char data-type, it can contain ‘letters’ of the ASCII alphabet
zero, in the ASCII alphabet, is the null character
When programming in C there is a difference between how strings are represented and how single characters are represented
20
The C Language
Strings, continuedCharacter Data
The data type for character data is char
We can assign any of the 256 ‘letters’ of the ASCII alphabet to a char
We can assign the ‘letter’ by using its numeric representation:char myChar;myChar = 65;
We can assign the ‘letter’ by enclosing it in single quotes:char myChar;myChar = ‘A’;
The above assignments perform the same action
21
The C Language
Strings, continuedString Data
The data type for each character of the string is char
The string is really an array of char data types
We represent a string by enclosing it in double quotes:
"this is a string"
""
The second example is an empty string, or null string
In both cases there is an IMPLICIT null character terminating the string
22
The C Language
Strings, continuedWhat does the string look like in memory?
Based on these definitions being found in your program:
...char myString[20];...strcpy(myString, “this is a string”);...
The strcpy() is a predefined function that performs a STRingCoPY - it is like saying, in pseudocode:myString = "this is a string"
... t h i s a s t r i n g \0 ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
i s
Memory Reserved for myString
23
The C Language
Strings, continuedWhen deciding on how much memory to reserve for a string be sure to include one position for the null-terminator
What would be the result of:
myString[8] = '1';
On the following string in memory:
... t h i s a s t r i n g \0 ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
i s
Memory Reserved for myString
24
The C Language
Strings, continuedWhen deciding on how much memory to reserve for a string be sure to include one position for the null-terminator
What would be the result of:
myString[8] = 0;
On the following string in memory:
... t h i s 1 s t r i n g \0 ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
i s
Memory Reserved for myString
25
The C Language
Strings, continuedFormatted output of strings - printf()
A new conversion code is used: %s
This tells the compiler to treat the array as a string of characters
The function will print the string up to but not including the null-terminating character '\0'
The flags and minimum width attributes can still be used
Based on what you already know, what does the following mean? (assuming txnDesc has been declared a string)
printf(“%-64s\n”, txnDesc);
26
The C Language
Strings, continuedUnformatted output of strings - puts()
The function prototype of puts() is:
int puts(char *ptrString);
If the function was successful, it returns a value >= 0 (a non-negative integer)
If the function failed, it returns EOF EOF is a value defined by the compiler through a #define statementit is a value < 0
This function will AUTOMATICALLY output a new-line character after outputting all of the characters of the string
27
The C Language
Strings, continuedFormatted input of strings - scanf()
Again, the %s conversion code is used
The following statement will read a string of data up to the first white-space character:
scanf("%s", myString);
The function stores the new-line character (if encountered)
28
The C Language
Strings, continuedConsider the following code:
#include <stdio.h>void main(void){ char strData[10];
scanf(“%s”, strData);
printf(“Read: %s\n”, strData);}
What would happen if the user typed in:
a_very_long_and_arduous_journey,_is_this_course_on_C!
29
The C Language
Strings, continuedA better solution would be:
#include <stdio.h>void main(void){ char strData[10];
scanf(“%9s”, strData); /* remember to leave a spot for the null */
printf(“Read: %s\n”, strData);}
Now what would happen if the user typed in:
a_very_long_and_arduous_journey,_is_this_course_on_C!
30
The C Language
Strings, continuedUnformatted input of strings - gets()
The function prototype of gets() is:
char *gets(char *ptrString);
This function will AUTOMATICALLY replace the new-line character with a null-terminator
If the function was successful, it returns a pointer to the same input string
If the function was unsuccessful, it returns NULLNULL is a value defined by the compiler through a #define statementit is a pointer to nothing
THIS IS A DANGEROUS FUNCTION AS YOU CAN EASILY CORRUPT MEMORY WITH AN UNCONTAINED READ – a better function is fgets() which will be introduced with file processing.
31
The C Language
Strings, continuedPredefined string manipulation commands:
They all have the same basic format
strxxx( parameters )
When working with strings, the computer will do NO checking on lengths
It your responsibility to ensure that when you manipulate a string you do not overrun memory
There is a specific header file associated with the predefined string functions:
#include <string.h>
32
The C Language
Strings, continuedString Copy:
char *strcpy(char *stringTo, char *stringFrom);
This function takes a string pointed to by stringFrom and copies it to the location pointed to by stringTo (including the null-terminator)
The function returns a pointer to stringTo
The following is an example of memory overrun:#include <stdio.h>#include <string.h>void main(void){ char strTo[5]; char strFrom[15]; strcpy(strFrom, “This fails”); strcpy(strTo, strFrom);}
33
The C Language
Strings, continuedString-Number Copy:
char *strncpy(char *stringTo, char *stringFrom, int size);
This function copies no more than size characters
If stringFrom is less than size, then stringTo will be padded to size characters using nulls
If stringFrom is greater than size, then only size characters will be copied - NO null-terminator will be placed in stringTo
34
The C Language
Strings, continuedString Length:
int strlen(char *string);
This function returns the number of characters in the string (not including the null-terminator)
35
The C Language
Strings, continuedString Compare:
int strcmp(char *string1, char *string2);
This function will compare two strings character-by-character
If the two strings are identical, the function returns zero
Otherwise, it returnsa value < 0 if string1 < string2, ora value > 0 if string1 > string2
You need to reference an ASCII table to determine the order, or collating sequence, of the 'letters'
For example 'a' > 'A' according to the ASCII table
36
The C Language
Strings, continuedString-Number Compare:
int strncmp(char *string1, char *string2, int size);
This function will compare two strings character-by-character
The test will stop when a null-terminator is encountered, OR size characters of string1 have been tested - whichever occurs first
37
The C Language
Strings, continuedString Concatenate:
char *strcat(char *stringTo, char *stringFrom);
This function will concatenate stringFrom to the end of stringTo
Remember that there must be enough memory set aside to contain both the contents of stringTo and stringFrom
The function returns a pointer to stringTo
The null-terminator in stringTo is replaced by the first character of stringFrom
All of stringFrom is copied to the end of stringTo until reaching the null-terminator of stringFrom
38
The C Language
Strings, continuedString-Number Concatenate:
char *strncat(char *stringTo, char *stringFrom, int size);
If the length of stringFrom is less than size, then the function will behave as if the strcat() function was used
If the length of stringFrom is greater than size, then size characters are appended to stringTo followed by a null-terminator
39
The C Language
Strings, continuedWhat would be the output of the following program:
#include <stdio.h>#include <string.h>void main(void){ char str1[10]; char str2[10]; strcpy(str1, “Testing”); printf(“Length is %d\n”, strlen(str1)); strcpy(str2, str1); printf(“String2 = %s\n”, str2);
if (strcmp(str1, str2) == 0) printf(“Both strings are the same\n”);
str1[4] = ‘\0’; strncat(str1, str2, 3); printf(“String1 is now: %s\n”);
if (strncmp(str1, str2, 4) == 0) printf(“The strings are still equal\n”);}