Hello friends,
I'm a beginner in C programming. One of my friends asked me to write a
program in C.The purpose of the program is print 1 to n without any
conditional statement, loop or jump.
How is it possible? Please help me.
Thanks in advance.
There is no way to know if it can be accomplished.
I guess that printf() has conditional statements, loops and jumps.
But besides the recursive solutions and the short circuit evaluation
hints, you could also write a program that writes the program.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc > 1) {
const int count = atoi(argv[1]);
int i;
puts("/* solution: */");
puts("#include <stdio.h>");
puts("int main(void)");
puts("{");
for (i = 1; i <= count; i++)
printf("puts(\"%d\");\n", i);
puts("return 0;");
puts("}");
}
return 0;
}
Now, one might object that the program that writes the program uses
conditional statements, jumps and loops. But then again, probably
printf() does as well so the answer might well be "no" in the case
that no tool using those tools can be used.
At any rate, I think your instructor is an idiot to give you this kind
of assignment. It's like teaching someone with a giant toolbox of
tools to overhaul an engine using a pipe wrench and a ball peen
hammer.
There are some restrictions that make sense. For instance, I taught C
to students for which many were long time COBOL programmers. So I
expressly forbade the use of goto in programming assignments with the
caveat that in the real world they could use all the gotos that they
want -- just not in my class. I wanted them to think about how to
program without using it. And I wanted to be able to understand the
programs that they turned in more easily also.
If he wants you to use recursion, he should have given you that hint
(in which case it would not have been an idiotic requirement). But to
make a beginning student guess that they are going to have to use
recursion is foolishness. For someone who has been programming C for
a decade, recursion will instantly be recognized as a solution. For
someone who has never programmed, it is doubtful that they would think
of using recursion without outside help. For that reason, I think it
is an approach that encourages plaugiarism.