# Week 8 Arrays Part 2 String & Pointer

## Presentation on theme: "Week 8 Arrays Part 2 String & Pointer"— Presentation transcript:

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

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

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

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

EKT120: Computer Programming
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[]) { ….. …. } Sem1-06/07 EKT120: Computer Programming

Initialize all elements inside array x[ ] to 0
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] Sem1-06/07 EKT120: Computer Programming

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]); } Store Read Sem1-06/07 EKT120: Computer Programming

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

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

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

EKT120: Computer Programming
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 maxIndex=counter maxIndex=1, counter = 2. exit for loop return maxIndex=1. x 2 6 3 x[0] x[1] x[2] Sem1-06/07 EKT120: Computer Programming

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

How Arrays are passed in a function call
#include <stdio.h> 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); Sem1-06/07 EKT120: Computer Programming

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); sumArray (listA, arraySize); copyArray (listA, listB, arraySize); return 0; } Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming
Sample Program #include <stdio.h> 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); printf ("Values in array3 by row are : \n"); printArray (array3); return 0; } // end of main Sem1-06/07 EKT120: Computer Programming

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

EKT120: Computer Programming
Output Values in array1 by row are : 1 2 3 4 5 6 Values in array2 by row are : 4 5 0 Values in array3 by row are : 1 2 0 4 0 0 Compare with the following………. 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 } }; Sem1-06/07 EKT120: Computer Programming

Details…………review lecture W7 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. Details…………review lecture W7 string Sem1-06/07 EKT120: Computer Programming

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

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 <stdio.h> #include <string.h> 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 ("\nSize of mystring is %d", sizeof (mystring));// size of string Good Bye return 0; } Sem1-06/07 EKT120: Computer Programming

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

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

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

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

Sample Program To convert a string to uppercase
#include <stdio.h> #include <string.h> 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 ); } Output Enter in a name in lowercase ahmad The name in uppercase is AHMAD Sem1-06/07 EKT120: Computer Programming

Controlling the Case of a Character
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? Sem1-06/07 EKT120: Computer Programming

String Conversion Functions
In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point values Sem1-06/07 EKT120: Computer Programming

Comparison Functions of the String
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 > 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 Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming
ASCII Table ASCII Character Set 1 2 3 4 5 6 7 8 9 nul soh stx etx eot enq ack bel bs ht If vt ff cr so si dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us sp ! # \$ % & ` ( ) * + , - . / : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ a b 10 d e f g h i j k l 11 n o p q r s t v 12 x y z { | } ~ del Sem1-06/07 EKT120: Computer Programming

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

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

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

EKT120: Computer Programming
Output 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 "programming" is greater than "computer" up to 7 characters Sem1-06/07 EKT120: Computer Programming

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