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

相关推荐
倒头就睡的小比特1 天前
算法竞赛C++常用的STL
c++·算法
weilx12341 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼1 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
Smileyqp沛沛1 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark1 天前
大规模并行计算中的负载均衡算法研究4
算法
吞下星星的少年·-·1 天前
C++ 萌新语法入门篇
c++·算法比赛