The eighth chapter of the post-curriculum planning of C + + primer

Source: Internet
Author: User

1. Write usually requires a parameter (the address of the string). string and print functionality.

Just. Assuming that the second argument (int type) is provided, and this parameter is not 0, the number of times the function prints the string quantity for that function will be called (meaning that the number of times the string is printed does not equal the value of the second parameter.) equals the number of times the function was called). Yes, it's a ridiculous function. But it allows readers to use some of the techniques described in this chapter.

Use this function in a simple program. To demonstrate how the function works. Code:

#include <iostream>using namespace std;void Show (const char * A, int b=0); void Show (const char * A, int b) {    Stati c int uses = 0;    int lim = ++uses;    cout << "First" << uses << "call. \ n";    if (b==0)        lim = 1;    for (int i=0; i<lim; i++)        cout <<a<<endl;} int main () {    int i;    const char * p = "Hello world\n";    cout << "Number of input function calls:";    Cin >> I;    while (i>=0)    {        cout << "parameter n is:" <<i;        Show (P, i);        i--;    }    cout << "Default n is 0:";    Show (p);    return 0;}    
Execution Result:

2.The candybar structure is full of 3 members. The first member stores the brand name of the candy bar. the second member stores the weight of the candy bar (which may have decimals). Third member storage candy barof calories (integers).

Please write a program. It uses a function such as a reference to CandyBar, a char pointer, a double, and an int as a parameter. The corresponding struct member is set with the last 3 values . The default values for the last 3 parameters are "Millennium Munch", 2.85, and 350, respectively. In addition, The program includes a reference to CandyBar as the number of parameters. and displays the structure contents of the function.

please use const as much as possible . Code

#include <iostream> #include <cstring>using namespace std;const int max=60;struct candybar{Char Brand[max];    Double weight; int energy;}; void Init (CandyBar & CB, const char *BR = "Millennium Munch", double we = 2.85, int ca =); void Displa    Y (const CandyBar & CB); int main () {CandyBar candybar;    cout << "Default candybar is:" <<endl;    Init (CandyBar);    Display (CandyBar);    Char Newbrand[max];    Double newweight;    int newenergy;    cout << "Please enter new CandyBar data:" <<endl;    cout << "Brand:";    Cin.get (Newbrand, MAX);    cout << "Weight:";    Cin >> Newweight;    cout << "energy:";    Cin >> Newenergy;    Init (CandyBar, Newbrand, Newweight, Newenergy);    Display (CandyBar); return 0;}    void Init (CandyBar &cb,const char *br, double we, int CA) {strcpy (Cb.brand, BR);    Cb.weight = we; Cb.energy = CA;}    void display (const candybar &AMP;CB) {cout << "new candybar: \ n"; cout << "Brand:" << cb.brand<<endl;    cout << "Weight:" <<cb.weight<<endl; cout << "energy:" &LT;&LT;CB.ENERGY&LT;&LT;ENDL;}
Execution Results

3.Write a function that takes a reference to a string object as a parameter and converts the contents of the string object to uppercase, using the function ToUpper ().

. Then write a program that uses a loop so that you can test the function with different inputs, the program performs the following things such as:

Enter a string (Q to quit): Go away
GO away
Next string (Q to quit): Good grief!
Good grief!
Next string (Q to quit): Q
Bye.
Code:
#include <iostream> #include <string>using namespace std;void wordupper (string &a); int main () {    String str;    cout << "Enter a string (1 to quit):";    Getline (CIN, str);    int i=0;    while (str! = "Q")    {        wordupper (str);        cout << str <<endl;        cout << "Next string (Q to quit):";        Getline (CIN, str);    }    cout << "bey!\n";    return 0;} void Wordupper (String &a) {    int i;    while (A[i])    {        A[i] = ToUpper (A[i]);        i++;}    }
Execution Result:

5.write the template function max5 (), which takes an array of 5 elements of type T as a parameter,and returns the largest element in the array (because the length is fixed, so you can use the hardcode, without having to pass the number of references). Use this function in a program to replace T with theAn array that includes 5 int values and an array of 5 dowble values to test theFunction.

Code:

#include <iostream>template<class t>t max5 (T ar[]) {    int n;    T max = ar[0];    for (n=1; n<5; n++)        if (Ar[n] > Max)            max = ar[n];    return Max;} const INT LIM = 5;int Main () {    using namespace std;    Double Ard[lim] = { -3.1, 8.1, -71.1, 34.4, 2.3};    int Ari[lim] = {2, 3, 9, 7};    Double MD;    int mi;    MD = MAX5 (ARD);    Mi = max5 (ARI);    cout << "Max double =" << MD <<endl;    cout << "Max int =" << mi <<endl;    return 0;}
Execution Result:

6.write the template function Maxn (), which will consist of an array of type T elements and a representation arrayAn integer of the number of elements as the number of parameters. and returns the largest element in the array. It is measured in the programtest, the program uses an array of 6 int elements and a number that includes 4 double elementsGroup to call the function. The program also includes a detailed set of char pointer arrays andThe number of pointers as a parameter, and returns the address of the longest string. Suppose there are multiple such charactersstring, it returns the address of the first of these strings. Use an array consisting of 5 string pointers tothe details of the test. Code:
#include <iostream> #include <cstring>template<class t>t maxn (T ar[], int n) {int i;    T max = ar[0];    for (I=1; i<n; i++) if (Ar[i] > max) max = ar[i]; return Max;}    template<> const char * MAXN (const char * arr[], int n) {const char * max = arr[0];    int i;    for (I=1; i<n; i++) if (strlen (Arr[i]) > strlen (max)) max = Arr[i]; return Max;}    int main () {using namespace std;    int ari[6] = {8,4,2,7,10,22};    Double Ard[4] = {-3.1, 8.1,-71.1, 34.4}; const char * char_arr[5] = {"Hello world!", "What is your name?", "I Love You", "is Wonderf    UL "," HI "};    cout << "The max Integer of array is:" << maxn (Ari, 6) <<endl;    cout << "The max double of array is:" << MAXN (ARD, 4) <<endl;    cout << "The max string of array is:" << maxn (Char_arr, 5) <<endl; return 0;}
Execution Result:

7.Change the program listing 8.14 so that the template function returns the sum of the array elements,Instead of displaying the contents of the array. The sum of the program thing and the sum of all debt.Code:
#include <iostream>template <typename t>t showarray (t arr[], int n), template <typename t>t Showarray (t   * arr[], int n); struct debts{char name[50]; double amount;};   int main (void) {using namespace std;   int things[6] = {13, 31, 103, 301, 310, 130};   struct debts Mr_e[3] = {{"Ima Wolfe", 2400.0}, {"Ura Foxe", 1300.0}, {"Iby Stout", 1800.0}};   double* Pd[3];   for (int i = 0; i < 3; i++) Pd[i] = &mr_E[i].amount;   cout<< "Listing Mr. E ' s counts of things:\n";   cout << Showarray (things,6) <<endl;   cout<< "Listing Mr E ' s debts:\n";   cout << Showarray (pd,3) <<endl; return 0;}   Template <typename t>t showarray (T arr[],int N) {using namespace std;   T total = 0;   cout<< "Template a\n";   for (int i = 0; i < n; i++) total +=arr[i]; return total;}   Template <typename t>t showarray (T * arr[], int n) {using namespace std;   T total = 0;   cout<< "Template b\n";for (int i = 0, i < n; i++) Total + = *arr[i]; return total;}
Execution Result:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvz3v1z2xlmjaxma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

The eighth chapter of the post-curriculum planning of C + + primer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.