Are you a great C coder? | Feb. 13, 2010

techgeek.in's Avatar, Join Date: Dec 2009
Skilled contributor
one day I and my friend were wondering what if C had no "Loops" ? Suppose C language has no "loops"(while, forloop, do while loop). Now, how are you going to implement a loop logic in C without while, for loop and do while loop ?? Explain with example..
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Approved
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Use if and goto. Not tested, cos I rarely use gotos:
Code:
int i=0;
:loop
printf("%d ");
i++;
if (i<10) goto loop;
techgeek.in's Avatar, Join Date: Dec 2009
Skilled contributor
dnt use GOTO...goto is not structured...
techgeek.in's Avatar, Join Date: Dec 2009
Skilled contributor
shabbir...wud u continue this? I think noone is able to give the ans...
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Lets do it buddy
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Answer must be tail recursion then:
Code:
void test2a(int i)
{
	if (i<10)
	{
		printf("%d ",i);
		test2a(i+1);
	}
}

void test2()
{
	test2a(0);
}
techgeek.in's Avatar, Join Date: Dec 2009
Skilled contributor
Quote:
Originally Posted by xpi0t0s View Post
Answer must be tail recursion then:
Code:
void test2a(int i)
{
	if (i<10)
	{
		printf("%d ",i);
		test2a(i+1);
	}
}

void test2()
{
	test2a(0);
}
Wow! at last...
Tail recursion is the only way to implement loop logic.. this process is used in PLT scheme.Take another example from me:-

Code:
# include<stdio.h>
# include<conio.h>

void ForLoop(int,int);
void main()
{

int i,n;
clrscr();
i=0;
n=10;
ForLoop(i,n);
getch();
}


void ForLoop(int i,int n)
{
static int count;
if(i==n)
printf("loop ended with count= %d", count);
else
{
count++;
i++;
ForLoop(i,n);
}
}
believe me you can implement any loop program using tail recursion.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Only if you've got enough stack space. If you haven't then you have to (a) use goto or (b) unroll the loop.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by xpi0t0s View Post
Only if you've got enough stack space. If you haven't then you have to (a) use goto or (b) unroll the loop.
Offtopic comment:
Have you seen your Visitor Message?