C++经典程序

在C++编程中,有几个被广泛认为是"经典"的程序。这些程序经常被用来教授C++的基础概念、演示特定的编程技巧,或者作为初学者学习和实践的好例子。下面是一些C++中的经典程序:

  1. Hello World程序

    cpp 复制代码
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!" << endl;
        return 0;
    }

    这是最基本的C++程序,用于演示如何输出文本到控制台。

  2. 阶乘程序

    cpp 复制代码
    #include <iostream>
    using namespace std;
    
    int factorial(int n) {
        if (n == 0) return 1;
        return n * factorial(n - 1);
    }
    
    int main() {
        int n;
        cout << "Enter a positive integer: ";
        cin >> n;
        cout << "Factorial of " << n << " = " << factorial(n) << endl;
        return 0;
    }

    这个程序展示了递归函数的使用,计算给定数的阶乘。

  3. Fibonacci数列程序

    cpp 复制代码
    #include <iostream>
    using namespace std;
    
    int fibonacci(int n) {
        if (n <= 1) return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    int main() {
        int n;
        cout << "Enter the number of terms: ";
        cin >> n;
        cout << "Fibonacci Series: ";
        for (int i = 0; i < n; i++) {
            cout << fibonacci(i) << " ";
        }
        cout << endl;
        return 0;
    }

    这个程序通过递归函数生成Fibonacci数列。

  4. 排序算法(如冒泡排序)

    cpp 复制代码
    #include <iostream>
    using namespace std;
    
    void bubbleSort(int arr[], int n) {
        for (int i = 0; i < n-1; i++)     
            for (int j = 0; j < n-i-1; j++) 
                if (arr[j] > arr[j+1])
                    swap(arr[j], arr[j+1]);
    }
    
    int main() {
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        int n = sizeof(arr)/sizeof(arr[0]);
        bubbleSort(arr, n);
        cout << "Sorted array: \n";
        for (int i=0; i < n; i++)
            cout << arr[i] << " ";
        cout << endl;
        return 0;
    }

    这个程序演示了基本的冒泡排序算法。

这些程序展示了C++的基本结构和一些常见的编程概念,如循环、递归、数组处理等。对于初学者来说,理解和实践这些程序是学习C++的一个很好的起点。

相关推荐
C雨后彩虹几秒前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD15 分钟前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法
Gomiko30 分钟前
C/C++基础(四):运算符
c语言·c++
苏小瀚34 分钟前
[算法]---路径问题
数据结构·算法·leetcode
freedom_1024_40 分钟前
【c++】使用友元函数重载运算符
开发语言·c++
zmzb01031 小时前
C++课后习题训练记录Day43
开发语言·c++
月明长歌1 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir1 小时前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法
t198751281 小时前
MATLAB水声信道仿真程序
开发语言·算法·matlab
赖small强1 小时前
【Linux C/C++开发】 GCC -g 调试参数深度解析与最佳实践
linux·c语言·c++·gdb·-g