C++基础练习 - Chapter 3

Review Questions

3.1 Enumerate the rules of naming variables in C++. How do they differ from ANSI C rules?

Answer:

Rules of naming variables in C++ are given below:
a. Any character from ‘a’ to ‘z’ or ‘A’ to ‘Z’ can be used.
b. Digit can be used but not at the beginnig.
c. Underscore can be used but space is not permitted.
d. A keyword cannot be used as variable name.
In C++, a variable can be declared any where in the program but before the using of the variable.
In C, all variables must be decleared at the beginning of the program.

3.2 Why does C++ have type modifiers(修饰符)?

Answer:

To serve the needs of various situations more precisely.

3.3 What are the applications of void data type in C++?

Answer:

Two normal uses of void are:
(1). to specify the return type of a function when it is not returning any value.
(2). To indicate any empty argument list to a function.

3.4 Can we assign a void pointer to an int type pointer? If not, why? Now can we achieve this?

Answer:

We cannot assign a void pointer to an int type pointer directly. Because to assign a pointer to another pointer data type must be matched. We can achieve this using casting (强制类型转换).
Example:
void *pt;
int *ip;
ip = (int *) pt;

3.5 Why is an array called a derived data type?

Answer:

Derived data types are the data types which are derived from the fundamental data types. Arrays refer to a list of finite number of same data types. The data can be accessed by an index number from 0 to n. Hence an array is derived from the basic data type, so array is called derived data type.

3.6 The size of a char array that is declared to store a string should be one larger than the number of characters in the string. Why?

Answer:

An additional null character must assign at the end of the string that’s why the size of char array that is declared to store a string should be one larger than the number of characters in the string.

3.7 The const was taken from C++ and incorporated in ANSI C, although quite differently. Explain.

Answer:

In both C and C++, any value declared as const cannot be modified by the program in any way. However there are some differences in implementation. In C++ we can use const in a constant expression, such as const int size = 10; char name[size]; This would be illegal in C. If we use const modifier alone, it defaults to int. C++ requires const to be initialized. ANSI C does not require an initialization if none is given, it initializes the const to 0. In C++ a const is local, it can be made as global defining it as external. In C const is global in nature, it can be made as local declaring it as static.

3.8 In C++ a variable can be declared anywhere in the scope. What is the significance of this feature?

Answer:

It is very easy to understand the reason of which the variable is declared.

3.9 What do you mean by dynamic initialization of a variable? Give an example.

Answer:

When initialization is done at the time of declaration then it is know as dynamic initialization of variable.
Example: float area = 3.14159 * rad * rad;

3.10 What is a reference variable? What is its major use?

Answer:

A reference variable provides an alias (alternative name) for a previously defined variable.
A major application of reference variable is in passing arguments to functions.

3.12 What is the application of the scope resolution operator :: in C++?

Answer:

A major application of the scope resolution operator is in the classes to identify the class to which a member function belongs.

3.13 What are the advantages of using new operator as compared to the junction malloc()?

Answer:

Advantages of new operator over malloc():

  1. It automatically computes the size of the data object. We need not use the operator size of.
  2. It automatically returns the correct pointer type, so that there is no need to use a type cast.
  3. It is possible to initialize the object while creating the memory space.
  4. Like any other operator, new and delete can be overloaded.

Debugging Exercises

3.1 Identify the error in the following program.

#include <iostream>
using namespace std;
int main()
{
    int num[] = {1,2,3,4};
    num[1] = num[1] ? cout<<"Sucess" : cout<<"Error";
    return 0;
}

Answer:

Wrong use of assignment and comparison operators.
Correction:

num[1] == num[1] ? cout<<"Sucess" : cout<<"Error";

then you can get “Sucess”.

3.2 Identify the errors in the following program.

#include <iostream>
using namespace std;
int main()
{
    int i = 5;
    while(i)
    {
        switch(i)
        {
            default:
            case 4:
            case 5:
            break;
            case 1:
            continue;
            case 2:
            case 3:
            break;
        }
       i--;
    }
    cout <<"Can show here?";

    return 0;
}

Answer:

The program will be continuing while value of i is 1 and value of i is not updating anymore. So infinite loop will be created.

3.3 Find errors, if any, in the following C++ statements.

  1. long float x;
  2. char *cp = vp; // vp is a void pointer
  3. int code = three; // three is an enumerator
  4. int sp = new; // allocate memory with new
  5. enum(green, yellow, red);
  6. int const sp = total;
  7. const int array_size;
  8. for(i = 1; int i<10; i++) cout << i <<“\n”;
  9. int &number = 100;
  10. int public = 1000;
  11. char name[3] = “USA”;

Answer:

Corrections:

  1. too many types, float x; or long int x; or double x;
  2. type must be matched, char cp = (char) vp;
  3. no error
  4. syntax error, int *sp = new int[10];
  5. tag name missing, enum color (green, yellow, red);
  6. address have to assign instead of content, int const *p = &total;
  7. C++ required a const to be initialized, const int array_size = 7;
  8. undefined symbol i, for(int i = 1; i < 10; i++)
  9. invalid variable name, int number = 100;
  10. keyword can not be used as a variable name, int publicX = 1000;
  11. array size of char must be larger than the number of characters in the string, char name[4] = “USA”;

Programming Exercises

3.1 Write a function using reference variables as arguments to swap the values of a pair of integers.

Answer:

#include <iostream>
using namespace std;

void swap(int &a, int &b);

int main()
{
    int x, y;
    cout << "Enter 2 integer value: " << endl;
    cin >> x >> y;
    swap(x, y);
    return 0;
}

void swap(int &a, int &b)
{
    cout << "Before swapping: a = "<< a << ", b = "<< b <<endl;
    int temp;
    temp = a;
    a = b;
    b = temp;
    cout << "After swapping: a = "<< a << ", b = "<< b <<endl;
    
}

3.2 Write a function that creates a vector of user given size M using new operator.

Answer:

#include <iostream>
using namespace std;

int main()
{
    int M;
    int *v;
    cout << "Enter vector size : " << endl;
    cin >> M;
    v = new int [M];
    cout << "to check your performance insert" << "M" << "integer value" << endl;
    
    for(int i=0; i<M; i++)
    {
        cin >> v[i];
    }
    cout << "Given integer value are : " << endl;
    
    for(int j=0; j<M; j++)
    {
        if(j == M-1)
            cout << v[j];
        else
            cout << v[j]<<", ";
    }
    cout << endl;
    return 0;
    
}

3.3 Write a program to print the following outputs using for loops

1
22
333
4444
55555

Answer:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "Enter your desired number : " << endl;
    cin >> n;
    cout << endl << endl;
    
    for(int i = 1; i <= n; i++) // 控制打印行数
    {
        for(int j = 1; j <= i; j++) // 打印数字
        {
            cout << i;
        }
        cout << endl;
    }
    return 0;
    
}

3.4 An election is contested by five candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the vote cast for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a “spoilt ballot” and the program should also count the numbers of “spoilt ballot”.

Answer:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int count[5];
    int test;
    
    for(int i = 0; i < 5; i++)
    {
        count[i] = 0;
    }
    
    int spoilt_ballot = 0;
    cout << "You can vote candidate 1 to 5 " << endl
         << "Press 1 or 2 or 3 or 4 or 5 to vote "<< endl
         <<"Candidate 1 or 2 or 3 or 4 or 5 respectively"<<endl
         <<"Pres any integer value outside the range 1 to 5 for NO VOTE!!!  "
         <<"Press any negative value to terminate and see results:  "<<endl;
    
    while(1)
    {
        cin >> test;
        
        for(int j = 0; j <= 5; j++)
        {
            if(test == j)
            {
                count[j-1]++;
            }
        }
        if(test < 0)
        {
            break;
        }
        else if(test > 5)
        {
            spoilt_ballot++;
        }
    }
    
    for(int k = 1; k <= 5; k++)
    {
        cout << "Candidate " << k << setw(12);
    }
    cout << endl;
    cout << setw(7);
    
    for(int t = 0; t < 5; t++)
    {
        cout << count[t] << setw(13);
    }
    cout <<endl;
    
    cout << "spoilt_ballot " << spoilt_ballot << endl;
    
    return 0;    
}

3.5 An electricity board charges the following rates to domestic user to

discourage large consumption of energy:
For the first 100 units - 60P per unit
For the first 200 units - 80P per unit
For the first 300 units - 90P per unit
All users are charged a minimum of Rs. 50.00. If the total amount is more than Rs. 300.00 then an additional surcharge of 15% is added.
Write a program to read the names of users and number of units consumed and print out the charges with names.

#include <iostream>
using namespace std;

int main()
{
    int unit;
    float charge, additional;
    char name[40];
    
    while(1)
    {
       
        cout << "Enter consumer name & unit consumed : ";
        cin >> name >> unit;
        
        if(unit <= 100)     // 前100
        {
            charge = 50 + (60 * unit)/100;
        }
        else if(unit <= 200 && unit > 100)  // 前200
        {
            charge = 50 + (80 * unit)/100;
        }
        else if(unit <= 300 && unit > 200)// 前300
        {
            charge = 50 + (90 * unit)/100;
        }
        else if(unit > 300) // 大于300
        {
            charge = 50 + (90 * unit)/100;
            additional = (charge*15)/100;
            additional = charge + additional;
        }
        
        cout << "Name"<<"       " << "Charge"<<endl;
        cout << name << "       " << charge<<endl;
    }
    return 0;
    
}

相关推荐

  1. C++基础练习 - Chapter 3

    2024-07-17 16:42:01       20 阅读
  2. C++基础练习 - Chapter 2 (英文版)

    2024-07-17 16:42:01       30 阅读
  3. python 基础练习题3

    2024-07-17 16:42:01       32 阅读
  4. C语言基础练习——Day04

    2024-07-17 16:42:01       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 16:42:01       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 16:42:01       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 16:42:01       62 阅读
  4. Python语言-面向对象

    2024-07-17 16:42:01       72 阅读

热门阅读

  1. 如何成为一个厉害的人

    2024-07-17 16:42:01       23 阅读
  2. Web开发-LinuxGit基础6-本地-.gitignore

    2024-07-17 16:42:01       19 阅读
  3. 运动控制:步进电机同步带传动距离计算

    2024-07-17 16:42:01       19 阅读
  4. Spring与设计模式总览

    2024-07-17 16:42:01       20 阅读
  5. Avalonia中的数据验证

    2024-07-17 16:42:01       22 阅读
  6. [ptrade交易实战] 第十五篇 融资融券交易类函数

    2024-07-17 16:42:01       27 阅读
  7. 堆

    2024-07-17 16:42:01      20 阅读