Reputation:
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?
Upvotes: 0
Views: 4200
Reputation: 1210
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);
}
}
Upvotes: 4
Reputation: 2567
#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
Upvotes: 1