C 中的嵌套 for 循环可以递归地增加深度乘以用户给定的整数吗?

标签 c

我想避免嵌套 for 循环,因为它应该按用户给定的整数递归地增加深度。

因此,如果用户输入 3,则应像下面的示例一样嵌套。如果用户输入 6,则内部应再有三个循环!?

#include <stdio.h>

int main(void)
{
    // int depth_lvl = 3
    char n[] = {'a','b','c'};
    int i,j,y;
    int x = sizeof(n);

    for(i = 0; i < x; i++)// <---- LEVEL 1
    {
        printf("%c\n",n[i]);
        for(j = 0; j < x; j++)// <---- LEVEL 2
        {
            printf("%c%c\n",n[i],n[j]);
            for(y = 0; y < x; y++) // <---- LEVEL 3
            {
                printf("%c%c%c\n",n[i],n[j],n[y]);
            }
        }
    }

}

最佳答案

这是您正在寻找的东西吗? 该解决方案在每个级别使用递归和中间结果字符串,通过该中间结果字符串将当前级别的每个状态转移到下一个更深的级别。

#define MAX_DEPTH 6

void printRecursive(char n[], int x, int curDepth, char* result)
{
    // note: x is supposed to be sizeof(n).

    if (x > MAX_DEPTH)  // prohibit overflow of intermediateResult
        x = MAX_DEPTH;

    if (curDepth < x) {
        char intermediateResult[MAX_DEPTH+1];
        if (result)
            strcpy(intermediateResult,result);
        else
            strcpy(intermediateResult, "");

        for (int i=0;i<x;i++) {
            intermediateResult[curDepth] = n[i];
            intermediateResult[curDepth+1] = '\0';
            printRecursive(n,x,curDepth+1,intermediateResult);
        }
    }
    if (curDepth > 0)
        printf("%s\n", result);
}

int main(void)
{
    char n[] = {'a','b','c', 'd'};
    int x = sizeof(n);
    printRecursive(n, x, 0, NULL);
    return 0;
}

关于C 中的嵌套 for 循环可以递归地增加深度乘以用户给定的整数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42099155/

相关文章:

android - Bluez 架构 : Explain this Architecture

python - 与 0 进行比较以检查 Python 和 C 中的条件

C 编程 : Received data is written to a pointer

将一个结构转换为另一个结构以获取特定数据

在运行时检查 GCC 版本

c - 从内存缓冲区设置结构体的 int

c - 为什么这段代码运行没有任何输出(关于pthread)?

c - 解释一个c程序的输出

c - aio_write 在我的简单客户端/服务器程序中不起作用

c++ - 我如何知道 USB 设备是否已在使用中?