Thursday, June 11, 2009

print 1 to N

Write a C function that will print 1 to N one per each line on the
stdout where N is a int parameter to the function. The function should
not use while, for, do-while loops, goto statement, recursion, and
switch statement.

please do not post solutions using the ASM keyword and JUMP instructions inside it.

Solutions So Far:

Solution1:
Use setjmp and longjmp

Solution2:
they are used to invalidate the stack context, and return to the main function directly if inbetween more than 1 nested calls to other functions has been made. How will you use it for the desired purpose?


Solution3:
Is This Correct???

void nprint(int n)
{
char output[] = "1\n2\n3\n ... 32765\n32766\n32767\n";
char strn[5], *cp;

sprintf(strn, "%d", n);
cp = strstr(output, strn);
*(cp + strlen(strn) + 1) = '\0';

fputs(output, stdout);
}


Solution4:
I don't think this is a good question, i solved it using threads, but that's not really different of a recursion, changing the stack is just like a goto and the solution above use strstr that uses a loop, so I wouldn't spend much time trying to solve this shit question because all solutions will be crap.


Solution5:

Try This:
int i=1; //global

void a()
{
if(i==N) { printf("%d",i); exit(); }
else { printf("%d",i); i++; }
b();
}

void b()
{
if(i==N) { printf("%d",i); exit(); }
else { printf("%d",i); i++; }
a();
}


Solution6:
How about This:

#include
#include
#include
void main(int a,char **b)
{
int no,i,j;
char c[100]="ccprog ";
char d[100];
if(a==1)
{
printf("enter the value \n");
scanf("%d",&no);;
printf("%d\n",no);
no--;
if(no>0)
{
itoa(no,d,10);
strcat(c,d);
system(c);
}
}
else
{
no=atoi(b[1]);
printf("%d\n",no);
no--;
if(no>0)
{
itoa(no,d,10);
strcat(c,d);
system(c);
}
}
}



Do You Have Still Good Solution?
Please Share Here..

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.