Write a program that takes a positive integer n as input and prints all numbers from 1 to n in ascending order, without using any semicolons in the code.

For example, if N is 5, the output should be: 1 2 3 4 5. The program should work for any value of n, as long as it is a positive integer.

1. Using while loop

One way is to use the while loop to print all numbers between 1 and n without using a semicolon. The while loop can be used to combine multiple statements into one expression, and thus eliminating the need for semicolons. For example, the following code prints all numbers between 1 and 25 without using a semicolon:

C


C++



 
Here, printf("%d\n", i) and std::cout << i << "\n" prints the current value of i, followed by a newline character. The i <= n checks if the loop should continue or not, and the value of i is then incremented by one. The loop ends when i becomes greater than n. Note we can also use printf and std::cout inside a if-statement, as follows:

C


C++


2. Using Recursive main() function

Another way is to use recursion to print all numbers between 1 and n without using a semicolon. The idea is to call the main() function recursively, and with each call, print the next element in the series. We can use a static or a global variable to store information about the previous element.

C


C++



3. How to print numbers in the opposite order?

We can use recursion to print numbers in the opposite order from n to 1 without using a semicolon, using the similar logic as before. For example:

C


C++



 
Or we can use printf and std::cout inside a while loop.

C


C++