C Program to print numbers from 1 to N without using semicolon

C++Server Side ProgrammingProgramming

Here we will see a tricky solution of the problem. We shall print some numbers from 1 to N without using any semicolon.

We can solve this problem in two different methods. The first one is the Iterative method, and second one is recursive method.

Method 1

The printf() function returns the length of the string so it is a non-zero value. We can perform logical AND with the condition to print the result. Then increase the value of the counter.

Example Code

#include<stdio.h>
#define N 20
int main(int num, char *argv[]) {
while (num <=N && printf("%d ", num) && num++) {
//The while body is empty.
}
}

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Method 2

In the second method we will see how to do the same task using recursion. We will pass some argument with the main function. This main will be called recursively.

Example Code

#include<stdio.h>
#define N 20
main(int val) {
if (val <=N && printf("%d ", val) && main(val + 1)) {
//Body is empty
}
}

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Published on 15-Mar-2019 05:45:35