C: Looping without using looping statements or rec

2020-05-23 06:35发布

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?

标签: c loops
16条回答
爷、活的狠高调
2楼-- · 2020-05-23 07:04

You can use setjmp and logjmp functions to do this as shown in this C FAQ

For those who are curious to why someone have a question like this, this is one of the frequently asked questions in India for recruiting fresh grads.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-05-23 07:05

I'd go for using longjmp()

#include <stdio.h>
#include <setjmp.h>

void do_loop(int n) {
  int val;
  jmp_buf env;

  val = 0;

  setjmp(env);

  printf("%d\n", ++val);

  if (val != n)
    longjmp(env, 0);  
}

int main() {
  do_loop(7);
  return 0;
}
查看更多
仙女界的扛把子
4楼-- · 2020-05-23 07:06
    /// <summary>
    /// Print one to Hundred without using any loop/condition.
    /// </summary>
    int count = 100;
    public void PrintOneToHundred()
    {
        try
        {
            int[] hey = new int[count];
            Console.WriteLine(hey.Length);
            count--;
            PrintOneToHundred();
        }
        catch
        {
            Console.WriteLine("Done Printing");
        }
    }
查看更多
家丑人穷心不美
5楼-- · 2020-05-23 07:08

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);
}
查看更多
戒情不戒烟
6楼-- · 2020-05-23 07:08

You did not forbid fork().

查看更多
够拽才男人
7楼-- · 2020-05-23 07:09
 #include "stdio.h"

 #include "stdlib.h"

 #include "signal.h"

 int g_num;

 int iterator;

 void signal_print()

 {

        if(iterator>g_num-1)

                exit(0);

        printf("%d\n",++iterator);

 }

 void myprintf(int n)

 {

     g_num=n;

        int *p=NULL;

     int x= *(p); // the instruction is reexecuted after handling the signal

 }

 int main()

 {

        signal(SIGSEGV,signal_print);

        int n;

        scanf("%d",&n);

        myprintf(n);

        return 0;

 }
查看更多
登录 后发表回答