Date post: | 18-Jan-2018 |
Category: |
Documents |
Upload: | roland-carr |
View: | 234 times |
Download: | 0 times |
UniMAP SEM I - 10/11EKT 120 Computer
Programming 1
Lecture 8 – Arrays (2) and Strings
UniMAP SEM I - 10/11EKT 120 Computer
Programming 2
Outline8.1 Passing Arrays to Function8.2 Displaying Array in a Function8.3 How Arrays are passed in a function call8.4 Introduction to Strings8.5 Strings Type8.6 Character Array8.7 Declaration of Strings8.8 Fundamentals of Strings & Characters8.9 Initialization of Strings8.10 Assigning Values to Strings8.11 Calculation of Strings Size8.12 Strings Conversion Functions8.13 Comparison Functions of the Strings8.14 ASCII Table
UniMAP SEM I - 10/11EKT 120 Computer
Programming 3
Passing Arrays to Functionvoid fnInitialize (int aiList [ ]){
int iCount;
for (iCount = 0; iCount < 5; iCount ++)aiList [iCount] = 0;
}
Initializes int array of size 5 to 0.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 4
Array as Parameter in Function If size changes (lets say 10 or 20), need to write
another function. not practical and inflexible. Therefore, introduce another variable, iSize.void fnInitialize (int aiList [ ], int iSize){
int iCount;
for (iCount = 0; iCount < iSize; iCount ++)aiList [iCount] = 0;
}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 5
Constant Arrays Prevent the function from changing the values in array. Use word const in declaration. Function can modify array aiX but not array aiY.void fnExample (int aiX[ ], const int aiY[ ], int iSizeX[ ],int
iSizeY[ ]){
…..…..….….
}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 6
Initialize an array to 0void fnInitializeArray (int aiX[ ], int iSizeX){
int iCounter;
for (iCounter = 0; iCounter < iSizeX; iCounter ++)
aiX [iCounter] = 0;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 7
Read data and store it in an array
void fnFillArray (int aiX[ ], int iSizeX){
int iCounter;
for (iCounter = 0; iCounter < iSizeX; iCounter++)
scanf (“%d”, &aiX [iCounter]);}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 8
Displaying array in a function
void fnPrintArray (const int aiX[ ], int iSizeX){
int iCounter;
for (iCounter = 0; iCounter < iSizeX; iCounter ++)
printf (“%d”, aiX [iCounter]);}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 9
Find and return the sum of an array
int fnSumArray (const int aiX[ ], int iSizeX){
int iCounter;int iSum = 0;
for (iCounter = 0; iCounter < iSizeX; iCounter ++)iSum = iSum + aiX[iCounter];
return iSum;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 10
Find and return index of largest element of an array
int fnIndexLargestElement (const int aiX[ ], int iSizeX){
int iCounter;int iMaxIndex = 0;
for (iCounter = 0; iCounter < iSizeX; iCounter ++)if ( aiX[iMaxIndex] < aiX[iCounter] )iMaxIndex = iCounter;
return iMaxIndex;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 11
Copy an array into another array
void fnCopyArray (const int aiX[ ], int aiY[ ], int iLength)
{int iCounter;
for (iCounter = 0; iCounter < iLength; iCounter ++)
aiY[iCounter] = aiX[iCounter];}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 12
How arrays are passed in a function call
#include <stdio.h>
const int iArraySize = 10;
void fnInitializeArray (int aiX[], int iSizeX);void fnFillArray (int aiX[], int iSizeX);void fnPrintArray (const int aiX[], int iSizeX);int fnSumArray (const int aiX[], int iSizeX);int fnIndexLargestElement (const int aiX[], int iSizeX);void fnCopyArray (const int aiX[], int aiY[], int iLength);
UniMAP SEM I - 10/11EKT 120 Computer
Programming 13
How arrays are passed in a function call
int main(){
int aiListA [iArraySize] = {0};int aiListB [iArraySize];
fnPrintArray (aiListA, iArraySize);fnInitializeArray (aiListB, iArraySize);fnPrintArray (aiListB, iArraySize);fnFillArray (aiListA, iArraySize);fnPrintArray (aiListA, iArraySize);fnSumArray (aiListA, iArraySize);fnCopyArray (aiListA, aiListB, iArraySize);fnPrintArray (aiListB, iArraySize);
return 0;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 14
Sample Program#include <stdio.h>
void fnPrintArray (const int aiA[][3]); // function prototype
//function main begins program executionint main(){
//initialize array1, array2, array3int aiArray1 [2][3] = { {1, 2, 3}, {4, 5, 6} };int aiArray2 [2][3] = { 1, 2, 3, 4, 5 };int aiArray3 [2][3] = { {1, 2 }, { 4 } };
printf (“Values in array1 by row are : \n);fnPrintArray (aiArray1);printf ("Values in array2 by row are : \n");
fnPrintArray (aiArray2); printf ("Values in array3 by row are : \n"); fnPrintArray (aiArray3);return 0;} // end of main
UniMAP SEM I - 10/11EKT 120 Computer
Programming 15
Sample Program (cont…)//function to display array with two rows and three columnsvoid fnPrintArray (const int aiA[][3]){ int iRow; //row counter int iColumn; //column counter
//loop through row for (iROw = 0; iRow <= 1; iRow++) { //output column values for (iColumn = 0; iColumn <= 2; iColumn++) { printf ("%d ", aiA[iRow][iColumn]); } //end inner for
printf ("\n"); //start new line of output } //end outer for} //end function fnPrintArray
UniMAP SEM I - 10/11EKT 120 Computer
Programming 16
Sample Program (cont…)Output
Values in array1 by row are :1 2 34 5 6Values in array2 by row are :1 2 34 5 0Values in array3 by row are :1 2 04 0 0
UniMAP SEM I - 10/11EKT 120 Computer
Programming 17
What is a String? A string is a series of characters treated as a single
unit. Strings can be treated as array of type char used to
store names of people, places, or anything that involves a combination of letters.
A string may include letters, digits and various special characters such as +, -, *, ? and $.
String literals, or string constants, in C are written in double quotation marks ( “ ” ) as follows:“John Doe” (a name)“99999 Main Street” (a street address)“Kangar, Perlis” (a city and a state)“(012) 123-8755” (a telephone number)
What is a String? The data type string is a programmer-defined and is not
part of the C language. The C standard library supplies it. A string with no characters is called a null or empty string.
“ ” is the empty string. Every character in a string has a relative position in the
string. The position of the first character is 0, position of the
second is 1, and so on. The length of a string is the number of character in it. A string is accessed via a pointer to the first character in
the string. The value of a string is the address of its first character.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 18
UniMAP SEM I - 10/11EKT 120 Computer
Programming 19
ExampleString Position of a Character Length of the String
in the String“William Jacob” Position of ‘W’ is 0 13
Position of the first ‘i’ is 1Position of ‘ ’ (the space) is 7Position of ‘J’ is 8Position of ‘b’ is 12
“Mickey” Position of ‘M’ is 0 6Position of ‘i’ is 1Position of ‘c’ is 2Position of ‘k’ is 3Position of ‘e’ is 4Position of ‘y’ is 5
UniMAP SEM I - 10/11EKT 120 Computer
Programming 20
String Type To use the data type string, the program must
include the header file string.#include <string.h>
The statementstring acInfo = “Welcome”;declares acInfo to be string variable and also initializes info to “Welcome”.
The position of the first character, ‘W’, in the info is 0, the position of the second character, ‘e’, is 1, and so on.
The variable acInfo is capable of storing (just about) any size string.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 21
Character Array (string of characters)
char acInfo [10]; Can store “Welcome”, “Good Bye”.
char acName [50]; Able to store shorter strings than
total length. The last value in the string will be
a null character (‘\0’).
UniMAP SEM I - 10/11EKT 120 Computer
Programming 22
Declaration of Strings An example of declaration of an array (or string of
characters):
It is not necessary that this max size of 10 characters should at all the times be fully used. acInfo could store at any part of the program either the string of characters “Welcome” or the string “Good Bye”.
acInfo
char acInfo [10];can store a string up to 10
characters long, and may visualize itas below
UniMAP SEM I - 10/11EKT 120 Computer
Programming 23
Declaration of Strings (cont..) A null character, constant 0 or ‘\0’ can
be written at the end of the valid content of a string if the characters to be stored is shorter than its total length (10 in this case).
acInfo is an array of 10 elements of type char, could be represented by storing the strings of characters “Welcome” and “Good Bye” in the following way:
UniMAP SEM I - 10/11EKT 120 Computer
Programming 24
Declaration of Strings (cont..)
W
acInfo
e l c o m e \0
G eyBdoO \0
to indicateend of string indefinite
values
UniMAP SEM I - 10/11EKT 120 Computer
Programming 25
Fundamentals of Strings and Characters String declarations
Declare as a character array or a variable of type char *char acInfo[] = “Welcome";char *pcInfo = “Welcome";
Remember that strings represented as character arrays end with '\0'
acInfo has 8 elements Inputting strings
Use scanfscanf("%s", acWord);
Copies input into acWord[] Does not need & (because a string is a pointer (slide 18))
Remember to leave room in the array for the null character ('\0’)
UniMAP SEM I - 10/11EKT 120 Computer
Programming 26
Initialization of string Similar to array, but each character is enclosed
in ‘ ’ or “ ”. Example:
char acNewString[]={‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’}; char acNewString[]= “Welcome”;
‘\0’ is automatically inserted. The difference is that single quotes (‘) are
used to specify single character constants and null character must be added at the end of the sentence.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 27
Initialization of string (cont…) On the other hand, double quotes (“) are
constant that specify sequence of characters and always have a null character (‘\0’) automatically inserted at the end.char acNewString[]= {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’};
char acNewString[] = “Welcome”;
Single quotes – null char must be added
Double quotes – null char automatically inserted
UniMAP SEM I - 10/11EKT 120 Computer
Programming 28
The examples below are not valid for string of characters (array).
newstring = “Welcome”; //no [] and data type
newstring [] =“Welcome”; //no data type
newstring = {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’}; //no [] and data type
Initialization of string (cont…)
UniMAP SEM I - 10/11EKT 120 Computer
Programming 29
Assigning values to string The left hand side value of an assignation can only be
array items and not the entire array, a possible way to assign a string of characters to an array of char can be shown as:
acNewString[0] = ‘W’;acNewString [1] = ‘e’;acNewString [2] = ‘l’;acNewString [3] = ‘c’;acNewString [4] = ‘o’;acNewString [5] = ‘m’;acNewString [6] = ‘e’;acNewString [7] = ‘\0’;
UniMAP SEM I - 10/11EKT 120 Computer
Programming 30
Calculation of string size char is 1 byte, the total number of alphabets plus a null would be
the size of the string. Example program:#include <stdio.h>#include <string.h>
char acNewString[] = {'W','e','l','c','o','m','e','\0'};char acMyString[] = "Good Bye";
int main(){ printf ("Size of acNewString is %d", sizeof (acNewString)); //size of string Welcome printf ("\nSize of acMyString is %d", sizeof (acMyString));// size of string Good Byereturn 0;}
What is the output?
UniMAP SEM I - 10/11EKT 120 Computer
Programming 31
Character and string manipulation
Examples: a program may need to verify that an
ID number of first year students starts with ‘09’.
determine whether last three characters in a part number are valid.
Built-in functions available – makes it easier.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 32
Controlling the case of a character ‘K’ is not equal to ‘k’. You use:
if (cChoice == ‘K’ || cChoice == ‘k’)while (cChoice == ‘Y’ || cChoice == ‘y’)
Can use a function that temporarily converts the letter to uppercase or lowercase before comparing it.
strupr(charVariable)strlwr(charVariable)
UniMAP SEM I - 10/11EKT 120 Computer
Programming 33
Controlling the case of a character (Example)char cChoice;printf ( “Continue? (Y or N) : “);scanf (“%c”, &cChoice);while (strupr(cChoice) == ‘Y’){
…..…..…..
}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 34
Controlling the case of a character (Example)
char acName[];
printf (“Enter a name : “);scanf (“%s”, acName);strupr(acName);printf("The name in uppercase is %s",
acName );
UniMAP SEM I - 10/11EKT 120 Computer
Programming 35
Sample ProgramTo convert a string to uppercase #include <stdio.h>#include <string.h>
void main(){
char acName[20]; /* declare an array of characters 0-79 */
printf("Enter in a name in lowercase\n");scanf( "%s", acName );strupr(acName);printf("The name in uppercase is %s", acName );
}
Output
Enter in a name in lowercasejohnThe name in uppercase is JOHN
UniMAP SEM I - 10/11EKT 120 Computer
Programming 36
Controlling the case of a character Real value does not changed. The functions only affect characters of
letters or alphabets. Does not affect numbers and special characters such as $ and %.
If the character is already lowercase or uppercase, the function will not affect the real value. It will return the original value.
char cRepeat = ‘Y’;cLetter = strupr(cRepeat);
cLetter = ?
UniMAP SEM I - 10/11EKT 120 Computer
Programming 37
Strings Conversion Functions Conversion functions
In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point
values
Prototype Description double atof( const char *nPtr ) Converts the string nPtr to double. int atoi( const char *nPtr ) Converts the string nPtr to int. long atol( const char *nPtr ) Converts the string nPtr to long int. double strtod( const char *nPtr, char **endPtr )
Converts the string nPtr to double.
long strtol( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to long.
unsigned long strtoul( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to unsigned long.
UniMAP SEM I - 10/11EKT 120 Computer
Programming 38
Strings Comparison Functions Comparing strings
Computer compares numeric ASCII codes of characters in string
int strcmp( const char *s1, const char *s2 ); Compares string s1 to s2 Returns a negative number if s1 < s2, zero if s1 ==
s2 or a positive number if s1 > s2int strncmp( const char *s1, const char *s2, size_t
n ); Compares up to n characters of string s1 to s2 Returns values as above
UniMAP SEM I - 10/11EKT 120 Computer
Programming 39
ASCII TableASCII Character Set
0 1 2 3 4 5 6 7 8 9
0 nul soh stx etx eot enq ack bel bs ht1 If vt ff cr so si dle dc1 dc2 dc32 dc4 nak syn etb can em sub esc fs gs3 rs us sp ! “ # $ % & `4 ( ) * + , - . / 0 15 2 3 4 5 6 7 8 9 : ;6 < = > ? @ A B C D E7 F G H I J K L M N O8 P Q R S T U V W X Y9 Z [ \ ] ^ _ ’ a b C
10 d e f g h i j k l M11 n o p q r s t U v W12 x y z { | } ~ del
UniMAP SEM I - 10/11EKT 120 Computer
Programming 40
Sample Program 1#include <stdio.h>#include <string.h>
int main(){ char acString1[ 20 ], acString2[ 20 ]; //declaration of acString1 and acString2 int iResult;
printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); iResult = strcmp( acString1, acString2 ); //compare between acString1 and acString2 if ( iResult > 0 ) printf( "\"%s\" is greater than \"%s\"\n",acString1, acString2 ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\"\n",acString1, acString2 ); else printf( "\"%s\" is less than \"%s\"\n",acString1, acString2 );
return 0;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 41
Sample Program 1 (cont…) Output
Enter two strings: computer programming"computer" is less than "programming"
Enter two strings: programming computer"programming" is greater than "computer"
UniMAP SEM I - 10/11EKT 120 Computer
Programming 42
Sample Program 2#include <stdio.h>#include <string.h>
int main(){ char acString1[ 20 ], acString2[ 20 ]; int iResult, iCompareCount; printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); printf( "How many characters should be compared: " ); scanf( "%d", &iCompareCount ); iResult = strncmp( acString1, acString2, iCompareCount ); if (iResult > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else printf( "\"%s\" is less than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); return 0;}
UniMAP SEM I - 10/11EKT 120 Computer
Programming 43
Sample Program 2 (cont…)OutputEnter two strings: computer programmingHow many characters should be compared: 7"computer" is less than "programming" up
to 7 characters
Enter two strings: programming computerHow many characters should be compared: 7"programming" is greater than "computer"
up to 7 characters
UniMAP SEM I - 10/11EKT 120 Computer
Programming 44
Built in Functions for String Handling strcat Appends a string strchr Finds first occurrence of a given character strcmp Compares two strings strcmpi Compares two strings, non-case sensitive strcpy Copies one string to another strlen Finds length of a string strlwr Converts a string to lowercase strnca t Appends n characters of string strncmp Compares n characters of two strings strncpy Copies n characters of one string to another strnset Sets n characters of string to a given character strrchr Finds last occurrence of given character in string strrev Reverses string strset Sets all characters of string to a given character strspn Finds first substring from given character set in string strupr Converts string to uppercase
UniMAP SEM I - 10/11EKT 120 Computer
Programming 45
End – Arrays (2) & Strings
Q & A!