Download presentation
Presentation is loading. Please wait.
Published byDwain Eaton Modified over 9 years ago
1
Introduction to Programming Lecture 8
2
String Handling Character is the building block of strings. Characters are represented inside the computer as numbers, e.g. ASCII You can write a program to print ASCII table.
3
String Initialization char name [ 20 ] ; name [ 0 ] = ‘G’ ; name [ 1 ] = ‘o’ ; name [ 2 ] = ‘o’ ; name [ 3 ] = ‘d’ ; name [ 4 ] = ‘\0’ ;
4
String Initialization char name [ 20 ] = “RPI” ; Array must be one character space larger than the number of printable character which are to be stored.
5
In C we have Used \nNew Line \tTab Character \0Null Character All C strings are terminated by Null character
6
Character Array in Memory char name [ 100 ] ; cout << “ Please enter your name ” ; cin >> name ;
7
Initializing an Array Initializing array of integers int c [ 10 ] = { 1,2,3,4,5,6,7,8,9,10 } ; int c [ ] = { 1,2,3,4,5,6,7,8,9,10 } ; For character arrays char name [ 100 ] = { ‘a’,b’,’c’,’0’,’1’ } ; char name [ 100 ] = “abc01“ ; char name [ ] = “Hello World“ ;
8
Character Arrays To read name from keyboard and display it on screen char name [ 100 ] ; cout << “ Please enter you name” ; cin >> name ; cout << name ;
9
Character Arrays Displaying name on screen using loop for ( i = 0 ; i < 100 ; i ++ ) { cout << name [ i ] ; }
10
Comparing Two arrays Array size should be equal int equal = 0 ; int num1 [ 100 ], num2 [ 100 ] ; for ( i = 0 ; i < 100 ; i ++ ) { if ( num1 [ i ] != num2 [ i ] ) { equal = 1 ; break ; } } if ( equal ==1 ) cout << “ The arrays are not equal” ; else cout << “ The arrays are equal” ; Condition :
11
Comparing Two Arrays AZMAT HAMEED Azmat Hameed
12
Exercise Self Study: cin.get(MAX), cin.get(str, MAX,‘$’) Input your name and display it in reverse order Determine the length of character array
13
Example #include main ( ) { int i ; char c ; for( i = 0; i < 256 ; i ++ ) { c = i ; cout << i << “\t” << c <<endl ; }
14
Header File ctype.h #include
15
ctype Functions int isdigit ( int c ) int isalpha ( int c ) int isalnum ( int c ) int isxdigit ( int c ) int islower ( int c ) int isupper ( int c ) int tolower ( int c ) int toupper ( int c ) int isspace ( int c ) int iscntrl ( int c ) int ispunct ( int c ) int isprint ( int c ) int isgraph ( int c )
16
cout << “Please enter a character string then press enter”; while ( ( c = getchar ( ) ) != ‘\n’ ) { if ( islower ( c ) ) lc ++ ; else if ( isupper ( c ) ) uc ++ ; else if (isdigit ( c ) ) dig ++; else if ( isspace ( c ) ) ws ++ ; else if ( ispunct ( c ) ) pun ++ ; else oth ++ ; } getchar ( ) ;
17
Character Strings A sequence of characters is often referred to as a character “ string ”. A string is stored in an array of type char ending with the null character '\0 '.
18
Character Strings A string containing a single character takes up 2 bytes of storage.
19
Character Strings
21
Characters vs. Strings
22
A string constant is a sequence of characters enclosed in double quotes. For example, the character string: char s1[2]= " a "; //Takes two bytes of storage. On the other hand, the character, in single quotes: char s2= `a `; //Takes only one byte of storage.
23
Example char message1[12] = "Hello world"; cout << message1 << endl; message1:
24
char message2[12]; cin >> message2; // type "Hello" as input message2:
25
Example 2: String I/O String can be input using the extraction operator >>, but one or more white spaces indicates the end of an input string. char A_string[80]; cout << "Enter some words in a string:\n"; cin >> A_string; cout << A_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. This END OF OUTPUT
26
getline The function getline can be used to read an entire line of input into a string variable. The getline function has three parameters: The first specifies the area into which the string is to be read. The second specifies the maximum number of characters, including the string delimiter. The third specifies an optional terminating character. If not included, getline stops at ‘\n’.
27
Example 3: getline char A_string[80]; cout << "Enter some words in a string:\n"; //80 is the size of A_string cin.getline(A_string, 80); cout << A_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. END OF OUTPUT
28
Example 4: getline Example char A_string[5], E_string[80]; cout << "Enter some words in a string:\n"; cin >> A_string; cin.getline (E_string, 9) ; cout << A_string << "#" << E_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. This# is a te END OF OUTPUT
29
String Copy Function in String Copy Function in void strcpy(char dest[], const char src[]); // copies string src into string dest example: char name1[16], name2[16]; strcpy(name1,"Chan Tai Man"); name1: name2: strcpy(name2,"999999999999999"); strcpy(name2,name1); ChanTaiMan\0??? ChanTaiMan\099\0 999999999999999\0
30
strcpy in strcpy in #include using namespace std; int main (){ char string_1[6] = "Short"; char string_2[17] = "Have a Nice Day"; char string_3[6] = "Other"; strcpy(string_1, string_2); return 0; }
31
String Length Check Function in String Length Check Function in // string prototype, already included in string.h //returns length of string(not counting'\0‘) //you don't need to include it in your program int strlen(const char[]); int string_length = strlen("abcde"); //string_length is set to 5.
32
String Length Check Function Example #include int main(){ char string_1[5] = "ABCD", string_2[10]="123456789"; cout << "String 1 = " << string_1 << endl; cout << "String 2 = " << string_2 << endl; strcpy(string_1,string_2,strlen(string_1)); cout << "After copying, string 1 = " << string_1<<endl; return 0; } //output: String 1 = ABCD String 2 = 123456789 After copying, string 1 = 1234
33
String Comparison int strcmp(char s1[], char s2[]); /*compares strings s1 and s2, returns /*compares strings s1 and s2, returns < 0 if s1 < s2 = 0 if s1 == s2 (i.e. strcmp returns false) > 0 if s1 > s2 */ */
35
Some Common Errors It is illegal to assign a value to a string variable (except at declaration). char A_string[10]; A_string = "Hello"; // illegal assignment Should use instead strcpy (A_string, "Hello");
36
Some Common Errors Some Common Errors The operator == doesn't test two strings for equality. if (string1 == string2) //wrong cout << "Yes!"; // illegal comparison Should use instead if (!strcmp(string1,string2)) cout << "Yes they are same!"; //note that strcmp returns 0 (false) if //the two strings are the same.
37
Pointers A variable that holds address value is called Pointer variable
38
Pointers 10 x 60000 Location Address of x
39
Declaring Pointer to Integer int *myptr ; myptr is pointer to an integer
40
Declaring Pointers double *x ; char *c ;
41
A string is a null terminated array of characters. – null terminated means there is a character at the end of the the array that has the value 0 (null). char *msg = “RPI”; 'R' msg zero (null) 'P''I'0 String Initialization
42
Example int *ptr ; int x ; x = 10 ; ptr = &x ;
43
Dereferencing Operator * *ptr is read as “The value of what ever ptr points to”
44
z = *ptr * 2 ;
45
Initializing Pointers ptr = &var ; ptr = 0 ; ptr = NULL ; 0 and NULL points to nothing
46
Example main ( ) { int numEmp ; …. funct ( &numEmp ) ; …. } void funct ( int *numEmp ) { cin >> *numEmp ; }
47
Declaring pointers int *ptr1, *ptr2, *ptr3 ;
48
Declaring pointers int *ptr, x ;
49
Declaring pointers int *ptr, x, a [ 10 ] ;
50
Swapping
51
Swap temp = x ; x = y ; y = temp ;
52
Example main ( ) { int x = 10, y = 20, * yptr, * xptr ; yptr = &y ; xptr = &x ; swap ( yptr, xptr ) ; }
53
Example swap ( int *yptr, int *xptr ) { … … … }
54
const int *const myptr = &x ; myptr is a constant pointer to an integer
55
const const int x = 10 ;
56
const const int *myptr = &x ; myptr is a pointer to a constant integer
57
Array int a [ 10 ] ; 1 2 3 4 5 6 7 8 9 10 a Starting Address of Array
58
Example 1 char myName [ ] = “Aqdus” ; char *myNamePtr = “Aqdus” ; Difference ? Constant Vs Variable Pointer
59
Multi-dimensional Arrays char multi [ 5 ] [ 10 ] ; where does multi point to in two dimension array? multi points to beginning of the array Lets take a look how multi-dimensional arrays are stored in the memory
60
Multi-dimensional Array in Memory 123410791114101725394558 Placed sequentially in the memory 1st row 1st col 2nd row 1st col [0] [1] [2] [3] [4] 3rd row 1st col What should happen if we increment multi ? What happens in single dimensional array ? It is important to know, what does multi point to ? and how to dereference it.
61
Dereferencing array element multi [ 2 ] [ 3 ] We derefer arrays by subscripts We derefer pointers by *
62
*multi ? It still holds the address: Address of the first row
63
Example 2 #include main ( ) { int multi [ 5 ] [ 10 ] ; cout << multi << endl ; cout << *multi ; cout << **multi ; } // *multi is still a pointer // We derefer the first element of the first row
64
Example 3 char multi [ 2 ] [ 2 ] ; multi[0][0]=‘a’; multi[0][1]=‘b’; multi[1][0]=‘c’; multi[1][1]=‘d’; cout << multi << endl; cout <<*multi<<endl; cout <<**multi;
65
multi + 3 *( multi + 3 ) *( multi + 3 ) + 3 *(*( multi + 3 ) + 3 ) // go to the fourth row // Beginning of the fourth row // address of fourth row, fourth column // value at fourth row, fourth column Alternative way of array manipulation
66
main ( ) { int multi [ 5 ] [ 6 ] ; int row, col ; int *ptr ; ptr = *multi ; for ( row = 0 ; row < 5 ; row ++ ) { for ( col = 0 ; col < 10 ; col ++ ) { multi [ row ] [ col ] = row * col ; } Example 4
67
Example 5 for ( row = 0 ; row < 5 ; row ++ ) { for ( col = 0 ; col < 10 ; col ++) { cout << *( ptr ++ ) << “ ”; } cout << endl ; } // Straight line storage // That's why when we pass multi dimensional array to a function we need to give the dimensions. // It needs to know the number of columns in the array // It needs to know where a row ends and the other start.
68
Pointers to Pointers Double dereferencing Pointer itself can be considered as an array
69
Array of Pointers Calculate the average age of the class : Store Names Memory allocation according to need: new The length of the string at initialization time of the character array, defines the size of the array Multidimensional character arrays: memory allocation = row X columns Equal space for all: No variable space Solution ?
70
Array of Pointers char *myArray [ 10 ] ; myArray is an array of 10 pointer to character
71
0xefffbab00xefffa0d0 hellotest\0 Initialization char *myArray [ ] = { “test ”, “ hello ” } ; Variable storage of strings: Hold the starting addresses of each strings: Arrays of pointers:
72
Storing Pointers in Array of Pointers int *p1, *p2, *p3 ; int *b [ 3 ] ; b [ 0 ] = p1 ; b [ 1 ] = p2 ; b [ 2 ] = p3 ;
73
Command Line Arguments argc argv ‘argc’ stands for a count of the number of arguments ‘argv’ stands for a vector of arguments
74
Example 4 main ( int argc, char **argv ) { cout << argc << "\n“ << *argv ; } Your program knows its name now
75
-> struct Employee { char title [50]; int year; }; Employee aEmployee; Employee * pEmployee; pEmployee = & aEmployee; cout title; Pointers to a data structure
76
Where are we Conclude last lecture Conclude last lecture Pointers to Pointers Pointers to Pointers Pointers with Multidimensional Arrays Pointers with Multidimensional Arrays Advantages of memory allocation in C++ Advantages of memory allocation in C++ Uses of memory allocation Uses of memory allocation
77
Practical Problem Problem statement Given tax brackets and given employee gross salaries, determine those employees who actually get less take home salary than others with lower initial income
78
Rule for tax deduction 0 –> 5,000No tax 5001 – >10,0005% Income Tax 10,001 – >20,00010% Income Tax 20,001 and more 15% Income tax
79
Example Net salary = Rs 10,000 Tax = 5% Amount Deducted = 5% of 10,000 = 500 Net amount after deduction = 10,000 - 500 = 9,500 Net salary = Rs 10,001 Tax = 10% Amount Deducted = 10% of 10,001 = 1,000.1 Net amount after deduction = 10,001 - 1,000.1 = 9,000.9
80
Storage Requirement One- dim arrays of integer lucky = 0 lucky = 1 0 0 0 0 0 0 0
81
Storage of salary 15,0005,000 210,0009,500 3 4 5 6 7 8 9 10 Grow Salary Net Salary After Deduction No of Emp.
82
Interface Requirements
83
Distribution of the Program Input Salary calculation Identification of the unlucky individuals Output
84
Detail Design Functions in the program getInput calculateSalary locateUnluckyIndividual displayOutput
85
Code #include void getinput ( int [ ] [ 2 ], int ) ; main ( ) { const int arraySize = 100 ; int sal [ arraySize ] [ 2 ] ; int lucky [ arraySize ] = { 0 } ; int numEmps ; cout << “Enter the number of employess “ ; cin >> numEmps ; getInput ( sal, numEmps ) ; }
86
Code getInput ( int sal [ ] [2], int numEmps ) { for ( i = 0 ; i < numEmps ; i ++ ) cin >> sal [ i ] [ 0 ] ; }
87
Tax Prog Detailed Code calculateSalary ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { for ( i = 0 ; i < numEmps ; i ++ ) { // netSalary = grossSalary – tax if ( sal [ i ] [ 0 ] <= 5000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ; }
88
Code else { if ( sal [ i ] [ 0 ] <= 10000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] - 0.05*sal [ i ] [ 0 ] ; }
89
Code else { if ( sal [ i ] [ 0 ] <= 20000 ) { sal [ I ] [ 1 ] = sal [ I ] [ 0 ] - 0.1 * sal [ I ] [ 0 ] ; }
90
Code else { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] - 0.15 * sal [ i ] [ 0 ] ; }
91
if ( sal [ i ] [ 0 ] >= 0 && sal [ i ] [ 0 ] <= 5000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ; } if ( sal [ i ] [ 0 ] > 5000 && sal [ i ] [ 0 ] < 10000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] - 0.05 * sal [ i ] [ 0 ] ; }... … …
92
if ( grossSalary > sal [ i ] [ 0 ] && netSalary < sal [ i ] [ 1 ] ) This logic will fail
93
Code void locateUnluckyIndividual ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { int i, j ; int grossSalary, netSalary ; for ( i = 0 ; i < numEmp ; i ++ ) { grossSalary = sal [ i ] [ 0 ] ; netSalary = sal [ i ] [ 1 ] ; for ( j = 0 ; j < numEmp ; j ++ ) { if ( grossSalary > sal [ j ] [ 0 ] && netSalary < sal [ j ] [ 1 ] ) { lucky [ i ] = 1 ; }
94
Code void displayOutput ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { for ( i = 0 ; i < numEmp ; i ++ ) { if ( lucky [ i ] == 1 ) { cout<< “Employee No.” << i+1 << “ is unlucky, Gross Salary = ” << sal [ i ] [ 0 ] << “ Net Salary = ” << sal [ i ] [ 1 ] << “\n” ; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.