递归实现C语言菱形图案打印

以下是使用递归函数实现的C语言程序,用于打印菱形图案。程序通过两个递归函数分别处理菱形的上半部分和下半部分,避免了循环结构:

c 复制代码
#include <stdio.h>

// 递归打印空格
void print_spaces(int n) {
    if (n <= 0) return;
    printf(" ");
    print_spaces(n - 1);
}

// 递归打印星号
void print_stars(int n) {
    if (n <= 0) return;
    printf("*");
    print_stars(n - 1);
}

// 递归打印上半部分(含中间行)
void print_upper(int current, int total) {
    if (current >= total) return;
    
    print_spaces(total - 1 - current);  // 打印前导空格
    print_stars(2 * current + 1);      // 打印星号
    printf("\n");
    
    print_upper(current + 1, total);    // 递归处理下一行
}

// 递归打印下半部分
void print_lower(int current, int total) {
    if (current >= total - 1) return;
    
    print_spaces(current + 1);          // 打印前导空格
    print_stars(2 * (total - 1 - current) - 1); // 打印星号
    printf("\n");
    
    print_lower(current + 1, total);    // 递归处理下一行
}

int main() {
    int line = 0;
    scanf("%d", &line);  // 输入行数
    
    print_upper(0, line);  // 打印上半部分(含中间行)
    print_lower(0, line);  // 打印下半部分
    
    return 0;
}

程序说明:

  1. 递归函数设计

    • print_spaces(int n):递归打印 n 个空格
    • print_stars(int n):递归打印 n 个星号
    • print_upper(int current, int total):递归打印菱形上半部分(含中间行)
    • print_lower(int current, int total):递归打印菱形下半部分
  2. 执行流程

    • 用户输入行数 line(如7)
    • print_upper(0, line) 从第0行开始递归,打印:
      • 空格数 = line-1-i
      • 星号数 = 2i+1
    • print_lower(0, line) 从第0行开始递归,打印:
      • 空格数 = i+1
      • 星号数 = 2(line-1-i)-1
  3. 示例输出(输入7):

    复制代码
       *
      ***
     *****
    *******





    复制代码
    *******
     *****
      ***
       *

此实现完全遵循递归范式,通过函数调用栈替代循环控制,符合题目要求。

相关推荐
aramae8 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
无敌贵点大王9 小时前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
Logic10110 小时前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Escalating_xu14 小时前
【C 语言项目】数组和函数综合实践:从零实现控制台扫雷游戏
c语言
Navigator_Z18 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
Logic10118 小时前
C语言/数据结构滑动窗口题解:替换k个字符后的最长连续相同字符子串(LeetCode 424)
c语言·数据结构·字符串·滑动窗口·时间复杂度·频率统计·算法题
free-elcmacom19 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
haluhalu.20 小时前
初识 Protobuf:微服务跨语言通信的一份契约
java·c语言·开发语言·c++·python
临期冰淇淋20 小时前
Unisoc 展锐平台Camera摄像头分辨率适配
linux·c语言·驱动开发
山下梅子酒22521 小时前
洛谷-入门-B2054
c语言