0

I want to print a statement n times without using a loop.

#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--;
    }
}

This is my code where I am printing a string 10 number of time using a while loop.

How can print it 10 number of time without using while or any loop?

2
  • 1
    The only other option is a recursive function (or to copy-paste the printf 10 times, but please don't do that). Commented Dec 22, 2020 at 15:14
  • regarding the statement: void main() That is not a valid signature for main() (although some non-compliant compilers will allow it.) The only valid signatures are: int main( void ) and int main( int argc, char *argv[] ) Commented Dec 23, 2020 at 2:34

2 Answers 2

4

You can do it by using recursive function .

A recursive function is a function that calls itself during its execution. The process may repeat several times, outputting the result and the end of each iteration.

Remove the while loop from the show() method, and use the if condition.

It will continuously call the method until the if condition goes false,

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

For better understanding, Full Code,

#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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this is the recursive equivalent of the loop. But it would be nicer to warn that when possible in real programming we prefere iterative methods when recursive ones.
Your answer would be a little bit better with an explanation of what you're doing, not only showing code to be copy-pasted. For example including at least a mention of recursion would be good to help the OP (and others) to search for something.
1
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
int main() {
   int x = 1;
   setjmp(buf); //set the jump position using buf
   printf("KrishnaKanth\n"); // Prints a name
   x++;
   if (x <= 5)
      longjmp(buf, 1); // Jump to the point located by setjmp
      
      return 0;
}

The output is:

KrishnaKanth
KrishnaKanth
KrishnaKanth
KrishnaKanth
KrishnaKanth

Another method: Calling main multiple times

#include<stdio.h> 
int main()
{ 
   static int counter = 1; // initialized only once
   printf("KrishnaKanth\n"); 
   if(counter==5) 
     return 0; 
   counter++; 
   main(); 
}

The output is:

KrishnaKanth
KrishnaKanth
KrishnaKanth
KrishnaKanth
KrishnaKanth

Comments