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++的一个很好的起点。

相关推荐
Lhan.zzZ5 小时前
笔记_2026.4.28_004
c++·ide·笔记·qt
wuminyu7 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
木喃的井盖7 小时前
无锁队列细节
c++·工程
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea8 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z8 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue8 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅9 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
KuaCpp9 小时前
C++面向对象(速过复习版)
开发语言·c++
MATLAB代码顾问10 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法