Home > Backend Development > C++ > body text

How Can Numbers Be Printed Sequentially from 1 to 1000 Without Loops or Conditional Statements in C?

Susan Sarandon
Release: 2024-11-26 17:37:10
Original
288 people have browsed it

How Can Numbers Be Printed Sequentially from 1 to 1000 Without Loops or Conditional Statements in C?

Solving the Enigma of Printing Numbers without Loops or Conditionals

The challenge of printing numbers sequentially from 1 to 1000 without relying on loop or conditional constructs intrigues programmers with its unconventional approach. How can such a seemingly straightforward task be accomplished without the fundamental tools of programming?

Unlocking the Solution in C

The solution, as demonstrated in the C code snippet below, lies in exploiting pointer arithmetic and recursion.

#include <stdio.h>
#include <stdlib.h>

void main(int j) {
  printf("%d\n", j);
  (&&main + (&exit - &main)*(j/1000))(j+1);
}
Copy after login

This code ingeniously utilizes function pointers and recursion to avoid the need for loops or conditionals. It calculates the address of the next recursive call based on the ratio of j/1000. By carefully manipulating the address of the main function, the program effectively simulates a "jump" to the next number in the sequence.

A Variant in Standard C

For those who prefer a more standard C approach, the following code eliminates the reliance on arithmetic on function pointers:

#include <stdio.h>
#include <stdlib.h>

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}
Copy after login

Both of these C code snippets demonstrate the possibility of printing numbers sequentially without loops or conditionals. They showcase the power of manipulating function pointers and recursion to overcome the seemingly insurmountable restriction.

The above is the detailed content of How Can Numbers Be Printed Sequentially from 1 to 1000 Without Loops or Conditional Statements in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template