Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sem1-06/07 EKT120: Computer Programming 1 Week 8 Arrays Part 2 String & Pointer.

Similar presentations


Presentation on theme: "Sem1-06/07 EKT120: Computer Programming 1 Week 8 Arrays Part 2 String & Pointer."— Presentation transcript:

1 Sem1-06/07 EKT120: Computer Programming 1 Week 8 Arrays Part 2 String & Pointer

2 Sem1-06/07 EKT120: Computer Programming 2 Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character Array Declaration of Strings Fundamentals of Strings & Characters Initialization of Strings Assigning Values to Strings Calculation of String Size String Conversion Functions Comparison Functions of the Strings ASCII Table

3 Sem1-06/07 EKT120: Computer Programming 3 Passing Array to Function void initialize (int list [ ]) { int count; for (count = 0; count < 5; count ++) list [count] = 0; } Initialize all element inside array list[ ] to 0 i.e: list [0]=0;. list [4]=0 passing array list [ ] to function

4 Sem1-06/07 EKT120: Computer Programming 4 Array as Parameters to Function If size changes (lets say 10 or 20), need to write another function. Introduce another variable, size without need to write another function. void initialize (int list [ ], int size) { int count; for (count = 0; count < size; count ++) list [count] = 0; }

5 Sem1-06/07 EKT120: Computer Programming 5 Constant Arrays Prevent the function from changing the values in array. Use word const in declaration. Function can modify array x but not array y. void example (int x[ ], const int y[ ], int sizeX[ ], int sizeY[]) {…..…..….….}

6 Sem1-06/07 EKT120: Computer Programming 6 Initialize an array to 0 void initializeArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) x [counter] = 0; } Initialize all elements inside array x[ ] to 0 i.e: x[0]=0,x[1]=0…….x[sizeX-1]

7 Sem1-06/07 EKT120: Computer Programming 7 Read data and store it in an array void fillArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) scanf (“%d”, &x[counter]); } Read Store

8 Sem1-06/07 EKT120: Computer Programming 8 Print the Array void printArray (const int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) printf (“%d”, x [counter]); }

9 Sem1-06/07 EKT120: Computer Programming 9 Find & return the sum of an array int sumArray (const int x [ ], int sizeX) { int counter; int sum = 0; for (counter = 0; counter < sizeX; counter ++) sum = sum + x [counter]; return sum; } Constant array int x[ ] with sizeX having element from 0 to (sizeX – 1) passed to sumArray function. Sum all elements in array x[ ] with size of sizeX x[0] + x[1] + ………x[sizeX - 1]

10 Sem1-06/07 EKT120: Computer Programming 10 Find & return Index of largest element of an array int indexLargestElement (const int x [ ], int sizeX) { int counter; int maxIndex = 0; for (counter = 0; counter < sizeX; counter ++) if ( x[maxIndex] < x[counter] ) maxIndex = counter; // copy counter to maxIndex return maxIndex; } Program to find the index of the largest element. Test each element in array x[ ] x[counter]  test each index starts from 0 to (sizeX – 1)

11 Sem1-06/07 EKT120: Computer Programming 11 Let sizeX = 3 x[sizeX] = x[3]={2,6,3} x[0]=2,x[1]=6,x[2]=3 Test each element to find the index of largest element. x[counter] = x[0]>maxIndex, 2>0 maxIndex=counter  maxIndex=0, repeat until counter = 2. x[counter]=x[1]>2, 6>2 maxIndex=counter  maxIndex=1, repeat until counter = 2. x[counter]=x[2]>6, but 3 6, but 3<6 maxIndex=counter  maxIndex=1, counter = 2. exit for loop return maxIndex= x x[0] x[1] x[2]

12 Sem1-06/07 EKT120: Computer Programming 12 Copy One Array Into Another Array void copyArray (const int x [ ], int y [ ], int length) { int counter; for (counter = 0; counter < length; counter ++) y [counter] = x [counter]; } Length = size of array x[ ], array x[ ] is a constant array y [counter] = x [counter]; // copy each element between arrays

13 Sem1-06/07 EKT120: Computer Programming 13 How Arrays are passed in a function call #include #include const int arraySize = 10; void initializeArray (int x [], int sizeX); void fillArray (int x [], int sizeX); void printArray (const int x [], int sizeX); int sumArray (const int x [], int sizeX); int indexLargestElement (const int x [], int sizeX); void copyArray (const int x [], int y [], int length);

14 Sem1-06/07 EKT120: Computer Programming 14 How Arrays are passed in a function call int main() { int listA [arraySize] = {0}; int listB [arraySize]; printArray (listA, arraySize); initializeArray (listB, arraySize); printArray (listB, arraySize); fillArray (listA, arraySize); printArray (listA, arraySize); sumArray (listA, arraySize); copyArray (listA, listB, arraySize); printArray (listB, arraySize); return 0; }

15 Sem1-06/07 EKT120: Computer Programming 15 Sample Program #include #include void printArray( const int a[][3]);// function prototype //function main begins program execution int main() { //initialize array1, array2, array3 int array1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; int array3 [2][3] = { {1, 2 }, { 4 } }; printf (“Values in array1 by row are : \n); printArray (array1); printf ("Values in array2 by row are : \n"); printArray (array2); printArray (array2); printf ("Values in array3 by row are : \n"); printf ("Values in array3 by row are : \n"); printArray (array3); printArray (array3); return 0; } // end of main

16 Sem1-06/07 EKT120: Computer Programming 16 Sample Program (cont…) Function To Output Array With Two Rows And Three Columns void printArray (const int a[][3]) { int i; //row counter int i; //row counter int j; //column counter int j; //column counter //loop through row //loop through row for (i = 0; i <= 1; i++) for (i = 0; i <= 1; i++) { //output column values //output column values for (j = 0; j <= 2; j++) for (j = 0; j <= 2; j++) { printf ("%d ", a[i][j]); printf ("%d ", a[i][j]); } // end inner for } // end inner for printf ("\n"); // start new line of output printf ("\n"); // start new line of output } // end outer for } // end outer for } // end function printArray

17 Sem1-06/07 EKT120: Computer Programming 17 Output Values in array1 by row are : Values in array2 by row are : Values in array3 by row are : int array1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; int array3 [2][3] = { {1, 2 }, { 4 } }; Compare with the following……….

18 Sem1-06/07 EKT120: Computer Programming 18 String………… Re-Cap from previous lecture….. Previous….array that contain numerical values in each array element. String….array that contain a single char in each element including the last element of these arrays is the null character (\0). String….arrays of characters Numerical array works element by element More convenient work with strings by using the address of the first element of string (advantage of pointer).   pointer becomes very important.   pointer becomes very important. Details…………review lecture W7 string

19 Sem1-06/07 EKT120: Computer Programming 19 Assigning values to string The left hand side value of an assignation can only be array items and not the entire array, the probable way to assign a string of characters to an array of char can be shown as: newstring[0] = ‘W’; newstring[1] = ‘e’; newstring[2] = ‘l’; newstring[3] = ‘c’; newstring[4] = ‘o’; newstring[5] = ‘m’; newstring[6] = ‘e’; newstring[7] = ‘\0’;

20 Sem1-06/07 EKT120: Computer Programming 20 Calculation of string size What are the result? char is 1 byte, the total number of alphabets plus a null would be the size of the string. Example program: #include #include char newstring[] = {'W','e','l','c','o','m','e','\0'}; char mystring[] = "Good Bye"; int main() { printf ("Size of newstring is %d", sizeof (newstring)); //size of string Welcome printf ("Size of newstring is %d", sizeof (newstring)); //size of string Welcome printf ("\nSize of mystring is %d", sizeof (mystring));// size of string Good Bye printf ("\nSize of mystring is %d", sizeof (mystring));// size of string Good Bye return 0; }

21 Sem1-06/07 EKT120: Computer Programming 21 Character & String manipulation Eg: –a program may need to verify that an ID number of first year students starts with ’04’. –Determine whether last three characters in a part number are valid. Built-in functions available – makes it easier.

22 Sem1-06/07 EKT120: Computer Programming 22 Controlling the Case of a Character ‘K’ is not equal to ‘k’. Previously use: if (choice == ‘K’ || choice == ‘k’) while (choice == ‘K’ || choice == ‘k’) Can use a function that temporarily converts the letter to uppercase or lowercase before comparing it. strupr(charVariable)strlwr(charVariable)

23 Sem1-06/07 EKT120: Computer Programming 23 Controlling the Case of a Character Example strupr char repeat; printf ( “Continue? (Y or N) : “); scanf (“%c”, &repeat); while (strupr(repeat) == ‘Y’) {…..…..…..} While loop performed even though the ‘y’ is entered. Function strupr temporarily converts the letter to uppercase

24 Sem1-06/07 EKT120: Computer Programming 24 char name[]; printf (“Enter a name : “); scanf (“%s”, name); strupr( name ); printf("The name in uppercase is %s", name ); Controlling the Case of a Character Example of strupr Function strupr temporarily converts the letter to uppercase even though user keyed lowercase.

25 Sem1-06/07 EKT120: Computer Programming 25 #include #include void main() { char name[80];/* declare an array of characters 0-79 */ printf("Enter in a name in lowercase\n"); scanf( "%s", name ); strupr( name ); // converts to uppercase printf("The name in uppercase is %s", name ); } Sample Program To convert a string to uppercase Output Enter in a name in lowercase ahmad The name in uppercase is AHMAD

26 Sem1-06/07 EKT120: Computer Programming 26 Real value does not changed. The functions only affect characters of letters or alphabet. Doesn’t affect numbers and special characters such as $ and %. If the character of already lowercase or uppercase, the function will not affect the real value. It will return the original value. char repeat = ‘Y’; letter = strupr(repeat); –Letter = ? affected or not? Controlling the Case of a Character

27 Sem1-06/07 EKT120: Computer Programming 27 Conversion functions –In (general utilities library) Convert strings of digits to integer and floating-point values String Conversion Functions

28 Sem1-06/07 EKT120: Computer Programming 28 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 int strncmp( const char *s1, const char *s2, size_t n ); –Compares up to n characters of string s1 to s2 –Returns values as above Comparison Functions of the String

29 Sem1-06/07 EKT120: Computer Programming 29 ASCII Character Set nulsohstxetxeotenqackbelbsht 1Ifvtffcrsosidledc1dc2dc3 2dc4naksynetbcanemsubescfsgs 3rsussp!“#$%&` 4()*+,-./ :; 7FGHIJKLMNO 8PQRSTUVWXY 9Z[\]^_’abC 10defghijklM 11nopqrstUvW 12xyz{|}~del ASCII Table

30 Sem1-06/07 EKT120: Computer Programming 30 #include #include int main() { char string1[ 20 ], string2[ 20 ]; //declaration of string1 and string2 char string1[ 20 ], string2[ 20 ]; //declaration of string1 and string2 int result; int result; printf( "Enter two strings: " ); printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); scanf( "%s%s", string1, string2 ); result = strcmp( string1, string2 ); // compare between string1 and string2 result = strcmp( string1, string2 ); // compare between string1 and string2 if ( result > 0 ) if ( result > 0 ) printf( "\"%s\" is greater than \"%s\"\n", string1, string2 ); printf( "\"%s\" is greater than \"%s\"\n", string1, string2 ); else if ( result == 0 ) else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\"\n", string1, string2 ); printf( "\"%s\" is equal to \"%s\"\n", string1, string2 ); else else printf( "\"%s\" is less than \"%s\"\n", string1, string2 ); printf( "\"%s\" is less than \"%s\"\n", string1, string2 ); return 0; return 0;} Sample program 1

31 Sem1-06/07 EKT120: Computer Programming 31 Enter two strings: computer programming "computer" is less than "programming" Enter two strings: programming computer "programming" is greater than "computer" Output

32 Sem1-06/07 EKT120: Computer Programming 32 #include #include int main() { char string1[ 20 ], string2[ 20 ]; char string1[ 20 ], string2[ 20 ]; int result, compareCount; int result, compareCount; printf( "Enter two strings: " ); printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); scanf( "%s%s", string1, string2 ); printf( "How many characters should be compared: " ); printf( "How many characters should be compared: " ); scanf( "%d", &compareCount ); scanf( "%d", &compareCount ); result = strncmp( string1, string2, compareCount ); result = strncmp( string1, string2, compareCount ); if ( result > 0 ) if ( result > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", printf( "\"%s\" is greater than \"%s\" up to %d characters\n", string1, string2, compareCount ); string1, string2, compareCount ); else if ( result == 0 ) else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", printf( "\"%s\" is equal to \"%s\" up to %d characters\n", string1, string2, compareCount ); string1, string2, compareCount ); else else printf( "\"%s\" is less than \"%s\" up to %d characters\n", printf( "\"%s\" is less than \"%s\" up to %d characters\n", string1, string2, compareCount ); string1, string2, compareCount ); return 0; return 0;} Sample program 2

33 Sem1-06/07 EKT120: Computer Programming 33 Enter two strings: computer programming How many characters should be compared: 7 "computer" is less than "programming" up to 7 characters Enter two strings: programming computer How many characters should be compared: 7 "programming" is greater than "computer" up to 7 characters Output

34 Sem1-06/07 EKT120: Computer Programming 34 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 strncat 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


Download ppt "Sem1-06/07 EKT120: Computer Programming 1 Week 8 Arrays Part 2 String & Pointer."

Similar presentations


Ads by Google