Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Looping without using looping statements or recursion

Tags:

c

loops

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?

like image 488
Prabhu R Avatar asked Oct 14 '09 08:10

Prabhu R


People also ask

Do a loop without using a loop in C?

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); ...

Can you program without loops?

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.

What can be used instead of for 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.


2 Answers

#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.

like image 51
qrdl Avatar answered Oct 06 '22 10:10

qrdl


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);
}
like image 22
Kjetil Joergensen Avatar answered Oct 06 '22 10:10

Kjetil Joergensen