Exercise 3:
1 // Exercise 3 for chapter 8: by TBNR_Gabriel 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5 using namespace std; 6 7 void convert(string & str); 8 9 int main() 10 { 11 string str; 12 cout << "Enter a string (q to quit): "; 13 getline(cin,str); 14 while (str != "q") 15 { 16 convert(str); 17 cout << str << endl; 18 cout << "Enter a string (q to quit): "; 19 getline(cin,str); 20 } 21 cout << "Done. "; 22 return 0; 23 } 24 25 void convert(string & str) 26 { 27 for (int i = 0; i < str.size(); i++) 28 str[i] = toupper(str[i]); 29 }
Exercise 5:
1 // exercise 5 for chapter 8: by TBNR_Gabriel 2 #include <iostream> 3 using namespace std; 4 5 template <typename T> 6 T large(T * arr); 7 8 int main() 9 { 10 int n1[5] = {2,5,3,4,1}; 11 double n2[5] = {2.1,3.3,4.4,1.3,4.2}; 12 int l1 = large(n1); 13 double l2 = large(n2); 14 cout << l1 << " " << l2 << endl; 15 return 0; 16 } 17 18 template <typename T> 19 T large(T * arr) 20 { 21 T maxi = arr[0]; 22 for (int i = 0; i < 5; i++) 23 { 24 if (arr[i] > maxi) 25 maxi = arr[i]; 26 } 27 return maxi; 28 }
Exercise 6:
1 // Exercise 6 for chapter 8: by TBNR_Gabriel 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 6 template <typename T> 7 T large(T * arr, int n); 8 9 template <> char * large(char ** arr, int n); 10 int main() 11 { 12 int n1[6] = {1,3,5,6,4,2}; 13 double n2[5] = {1.1,3.5,4.2,1.3,4.1}; 14 int l1 = large(n1, 6); 15 double l2 = large(n2, 5); 16 cout << l1 << " " << l2 << endl; 17 char a[30] = "aa"; 18 char b[30] = "bbb"; 19 char c[30] = "ccccc"; 20 char d[30] = "d"; 21 char e[30] = "ee"; 22 char * arr[5] = {a,b,c,d,e}; 23 char * ps = large(arr, 5); 24 cout << ps << endl; 25 return 0; 26 } 27 28 template <typename T> 29 T large(T * arr, int n) 30 { 31 T maxi = arr[0]; 32 for (int i = 0; i < n; i++) 33 { 34 if (arr[i] > maxi) 35 maxi = arr[i]; 36 } 37 return maxi; 38 } 39 40 template <> char * large(char ** arr, int n) 41 { 42 int length[n]; 43 for (int i = 0; i < n; i++) 44 length[i] = strlen(arr[i]); 45 int maxi = -1; 46 int index = 0; 47 for (int i = 0; i < n; i++) 48 { 49 if (length[i] > maxi) 50 { 51 maxi = length[i]; 52 index = i; 53 } 54 } 55 return arr[index]; 56 }