C++基础练习 - Chapter 3

news/2024/8/26 3:49:10 标签: c++, 开发语言

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;
    
}

http://www.niftyadmin.cn/n/5557926.html

相关文章

代码随想录算法训练营第五十五天|101.孤岛的总面积、102.沉没孤岛、103.水流问题、104.建造最大岛屿

101.孤岛的总面积 题目链接&#xff1a;101.孤岛的总面积沉没孤岛 文档讲解&#xff1a;代码随想录 状态&#xff1a;不会 思路&#xff1a; 步骤1&#xff1a;将边界上的陆地变为海洋 步骤2&#xff1a;计算孤岛的总面积 题解&#xff1a; public class Main {// 保存四个方…

(01)Unity使用在线AI大模型(使用百度千帆服务)

目录 一、概要 二、环境说明 三、申请百度千帆Key 四、使用千帆大模型 四、给大模型套壳 一、概要 在Unity中使用在线大模型分为两篇发布&#xff0c;此篇文档为在Python中使用千帆大模型&#xff0c;整体实现逻辑是&#xff1a;在Python中接入大模型—>发布为可传参的…

每天一个数据分析题(四百三十一)- 卡方检验

在列联表分析中&#xff0c;下列不能用卡方检验的是&#xff08;&#xff09; A. 多个构成的比较 B. 多个率的比较 C. 多个均值的比较 D. 以上都不是 数据分析认证考试介绍&#xff1a;点击进入 题目来源于CDA模拟题库 点击此处获取答案 数据分析专项练习题库 内容涵盖…

安全与认证:在Symfony中实现用户登录和权限管理

安全与认证&#xff1a;在Symfony中实现用户登录和权限管理 目录 简介Symfony 安全组件概述用户登录实现 配置安全系统创建用户实体配置用户提供者创建登录表单 权限管理实现 角色与权限配置控制器中的权限检查安全注解的使用 示例项目 项目结构示例代码 总结 1. 简介 在现…

鸿蒙语言基础类库:【@system.geolocation (地理位置)】

地理位置 说明&#xff1a; 从API Version 7 开始&#xff0c;该接口不再维护&#xff0c;推荐使用新接口[ohos.geolocation]。本模块首批接口从API version 3开始支持。后续版本的新增接口&#xff0c;采用上角标单独标记接口的起始版本。 导入模块 import geolocation from …

掌握Laravel的策略与授权门面:构建安全的Web应用

掌握Laravel的策略与授权门面&#xff1a;构建安全的Web应用 在构建Web应用时&#xff0c;确保适当的授权检查是至关重要的。Laravel框架提供了策略&#xff08;Policies&#xff09;和授权门面&#xff08;Policy Facades&#xff09;作为实现强大、灵活的授权系统的工具。本…

【机器翻译】基于术语词典干预的机器翻译挑战赛

文章目录 一、赛题链接二、安装库1.spacy2.torch_text 三、数据预处理赛题数据类定义 TranslationDataset批量处理函数 collate_fn 四、编码器和解码器Encoder 类Decoder 类Seq2Seq 类注意事项 五、主函数1. load_terminology_dictionary(dict_file)2. train(model, iterator, …

韦东山嵌入式linux系列-驱动进化之路:总线设备驱动模型-课后作业

在内核源码中搜索 platform_device_register 可以得到很多驱动&#xff0c;选择 一个作为例子&#xff1a; ① 确定它的名字 ② 根据它的名字找到对应的 platform_driver ③ 进入 platform_device_register/platform_driver_register 内部&#xff0c;分析 dev 和 drv 的匹配过…