首页 > 解决方案 > 如何在不使用循环的情况下多次打印?

问题描述

我想在n不使用循环的情况下打印语句时间。

#include<stdio.h>
#include<conio.h>
void show(char *n,int count);
void main()
{
    int x=10;
    char name[20]="zeeshann";
    clrscr();
    show (name,10);
    getch();
}

void show(char *n,int count)
{
    while(count>0)
    {
        printf("%s\n",n);
        count--;
    }
}

这是我的代码,我使用 while 循环打印字符串 10 次。

如何在不使用while或任何循环的情况下打印 10 次?

标签: c

解决方案


您可以通过使用递归函数来做到这一点。

递归函数是在执行过程中调用自身的函数。该过程可能会重复多次,输出结果和每次迭代的结束。

从 show() 方法中删除 while 循环,并使用 if 条件。

它将不断调用该方法,直到 if 条件变为 false,

void show(char *n,int count)
{
    if(count>0)
    {
        printf("%s\n",n);
        count--;
        show(n,count);
    }
}

为了更好地理解,完整代码,

#include<stdio.h>
#include<conio.h>
void show(char *n,int count);
void main()
{
    int x=10;
    char name[20]="zeeshann";
    clrscr();
    show (name,10);
    getch();
}

void show(char *n,int count)
{
    if(count>0)
    {
        printf("%s\n",n);
        count--;
        show(n,count);
    }
}

推荐阅读