I want to 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. Is it possible?
You should find something that mimics the loop. int f(int N) { if (N >= 900) f100(100); if (N >= 800) f100(100); if (N >= 700) f100(100); ... f100(n % 100); } int f100(int N) { if (N >= 90) f10(10); if (N >= 80) f10(10); if (N >= 70) f10(10); ...
Another way we can avoid using imperative loops is through recursion. Recursion is simple. Have a function call itself (which creates a loop) and design an exit condition out of that loop.
Array. filter, map, some have the same performance as forEach. These are all marginally slower than for/while loop. Unless you are working on performance-critical functionalities, it should be fine using the above methods.
#include <stdlib.h>
int callback(const void *a, const void *b) {
static int n = 1;
if (n <= N)
printf("%d\n", n++);
return 0;
}
int main(int argc, char *argv) {
char *buf;
/* get N value here */
buf = malloc(N); // could be less than N, but N is definitely sufficient
qsort(buf, N, 1, callback);
}
I think it doesn't count as recursion.
With blocking read, signals and alarm. I thought I'd have to use sigaction and SA_RESTART, but it seemed to work well enough without.
Note that setitimer/alarm probably are unix/-like specific.
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
volatile sig_atomic_t counter;
volatile sig_atomic_t stop;
void alarm_handler(int signal)
{
printf("%d\n", counter++);
if ( counter > stop )
{
exit(0);
}
}
int main(int argc, char **argv)
{
struct itimerval v;
v.it_value.tv_sec = 0;
v.it_value.tv_usec = 5000;
v.it_interval.tv_sec = 0;
v.it_interval.tv_usec = 5000;
int pipefds[2];
char b;
stop = 10;
counter = 1;
pipe(pipefds);
signal(SIGALRM, alarm_handler);
setitimer(ITIMER_REAL, &v, NULL);
read(pipefds[0], &b, 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With